我正在尝试使用 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/