【问题标题】:Mongoose Aggregate : limit the number of records in $groupMongoose Aggregate : 限制 $group 中的记录数
【发布时间】:2014-10-23 10:03:57
【问题描述】:

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

“对于每个具有给定 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 ] } ]

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

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以使用$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 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多