Mongoose Aggregate : 限制 $group 中的记录数 [英] Mongoose Aggregate : limit the number of records in $group

查看:18
本文介绍了Mongoose Aggregate : 限制 $group 中的记录数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

对于每个具有给定 oid 的玩家,选择玩得最多的游戏".这是我的游戏架构:

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

上面的代码返回如下:

[ { _id: 'yyyy', plays: [ 10,4,5 ] },
  { _id: 'xxxxx',
    plays: [ 28, 14, 10, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] } ]

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

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 ?

推荐答案

你可以使用$first 从排序管道的每组中的第一个文档中获取值:

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

因为您已在管道的前一阶段按 number_plays 降序排序,所以这将从每个 oid 组的文档中获取具有最高 number_plays 的值.

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.

这篇关于Mongoose Aggregate : 限制 $group 中的记录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆