2014-08-29 54 views
2

的记录数我想转换为使用猫鼬聚合方法有这样一句话:

“对于每一个球员给OID,选择已经玩过的最游戏”。 这里是我的游戏模式:

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 ] } ] 

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

回答

2

您可以使用$first取值从第一文档各组排序的管道中:

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