Cyril Gaillard
Cyril Gaillard

Reputation: 909

Mongoose Aggregate : limit the number of records in $group

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

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 ?

Upvotes: 2

Views: 1692

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

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.

Upvotes: 2

Related Questions