Mongoose Aggregate : limit the number of records in $group

前端 未结 1 1366
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-22 10:22

I am trying to convert this sentence using the Mongoose Aggregate method :

\"For each player with given oid, select the game that has been played the most\". Here is my

相关标签:
1条回答
  • 2021-01-22 11:05

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

    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.

    0 讨论(0)
提交回复
热议问题