猫鼬聚合:限制$ group中的记录数 [英] Mongoose Aggregate : limit the number of records in $group
问题描述
我正尝试使用Mongoose Aggregate方法转换此句子:
I am trying to convert this sentence using the Mongoose Aggregate method :
对于具有给定oid的每个玩家,选择玩得最多的游戏". 这是我的游戏架构:
"For each player with given oid, select the game that has been played the most". Here is my Game schema:
gameSchema = new mongoose.Schema({
game_name:{type:String},
game_id:{type:String},
oid:{type: String},
number_plays:{type:Number,default:0},
})
Game = mongoose.model('Game', gameSchema);
这是我正在使用的代码:
Here is the code I am using :
var allids = ['xxxxx','yyyy'];
Game.aggregate([
{$match: {'oid': {$in:allids}}},
{$sort: {'number_plays': -1}},
{$group: {
_id: '$oid',
plays:{$push:"$number_plays"},
instructions:{$push:"$game_instructions"}
}}
], function(err,list){
console.log(list);
res.end();
});
上面的代码返回以下内容:
The code above returns the following:
[ { _id: 'yyyy', plays: [ 10,4,5 ] },
{ _id: 'xxxxx',
plays: [ 28, 14, 10, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] } ]
问题在于它会返回所有游戏,而不是大部分已玩过的游戏.所以我的问题是:是否可以限制$ group中填充的字段?
The problem is that it returns all games, not the one that has been mostly played. So my question is : is it possible to limit the fields populated in the $group ?
推荐答案
您可以使用 $first
以便从已排序管道的每个组中的第一个文档中获取值:
You can use $first
to take values from the first doc in each group of a sorted pipeline:
var allids = ['xxxxx','yyyy'];
Game.aggregate([
{$match: {'oid': {$in:allids}}},
{$sort: {'number_plays': -1}},
{$group: {
_id: '$oid',
game_name: {$first: "$game_name"},
game_id: {$first: "$game_id"},
number_plays: {$first:"$number_plays"}
}}
], function(err,list){
console.log(list);
res.end();
});
由于您已经对number_plays
进行了降级,因此将使用每个oid
组文档中具有最高number_plays
的值.
Because you've sorted on number_plays
descending in the preceding stage of the pipeline, this will take the values from each oid
group's doc with the highest number_plays
.
这篇关于猫鼬聚合:限制$ group中的记录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!