Mongoose Aggregate:限制$ group中的logging数

我正在尝试使用Mongoose Aggregate方法来转换这个句子:

“对于每个玩家的oid,请select最有效的游戏”。 这是我的游戏架构:

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); 

这是我正在使用的代码:

 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(); }); 

上面的代码返回以下内容:

 [ { _id: 'yyyy', plays: [ 10,4,5 ] }, { _id: 'xxxxx', plays: [ 28, 14, 10, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] } ] 

问题是它会返回所有的游戏,而不是主要玩的游戏。 所以我的问题是:是否有可能限制填充在$组中的字段?

您可以使用$first从已sortingpipe道的每个组的第一个文档中获取值:

 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的前一个阶段中对number_plays进行了sorting,因此将从每个oid组的文档中获得最高number_plays