node.js - Mongoose 聚合 : limit the number of records in $group

标签 node.js mongodb mongoose aggregation-framework

我正在尝试使用 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 中填充的字段?

最佳答案

您可以使用$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 的文档中获取值.

关于node.js - Mongoose 聚合 : limit the number of records in $group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25567496/

相关文章:

mongodb - 字段名称中未捕获的异常 : can't have .

mongodb - 如何减少数据库条目的值

mongodb - 一个属性的 Mongoose 模式多引用

node.js - 什么查询或运算符将有助于找出 mongoDb 中数组元素的累积和

node.js - 由于使用 Node JS 进行迭代,API 变得缓慢

javascript - Node.JS 和同步数据库查询

node.js - 在 MongoDB 中存储由 socket.io 创建的套接字

python - 如何为python flask 应用程序提供结构

node.js - Mongoose 模式 setter 覆盖函数未被调用

node.js Amazon s3 如何检查文件是否存在