node.js 猫鼬对聚合结果进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26623141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:03:22  来源:igfitidea点击:

Mongoose sort the aggregated result

node.jsmongodbmongoosemongodb-queryaggregation-framework

提问by Renan Basso

I'm having a lot of difficulty in solving this mongodb (mongoose) problem.

我在解决这个 mongodb (mongoose) 问题时遇到了很多困难。

There is this schema 'Recommend' (username, roomId, ll and date) and its collection contains recommendation of user.

有这个模式“推荐”(用户名、房间 ID、ll 和日期),它的集合包含用户的推荐。

I need to get a list of most recommended rooms (by roomId). Below is the schema and my tried solution with mongoose query.

我需要获得最推荐的房间列表(按 roomId)。下面是模式和我尝试过的猫鼬查询解决方案。

var recommendSchema = mongoose.Schema({
    username: String,
    roomId: String,
    ll: { type: { type: String }, coordinates: [ ] },
    date: Date
})
recommendSchema.index({ ll: '2dsphere' });

var Recommend = mongoose.model('Recommend', recommendSchema);
Recommend.aggregate(
        {   
          $group: 
            { 
                _id: '$roomId', 
                recommendCount: { $sum: 1 } 
            }
        },
        function (err, res) {
            if (err) return handleError(err);
            var resultSet = res.sort({'recommendCount': 'desc'});

        }
    );

回答by Neil Lunn

The results returned from the aggregation pipeline are just plain objects. So you do the sorting as a pipeline stage, not as a separate operation:

从聚合管道返回的结果只是普通对象。因此,您将排序作为管道阶段进行,而不是作为单独的操作:

Recommend.aggregate(
    [
        // Grouping pipeline
        { "$group": { 
            "_id": '$roomId', 
            "recommendCount": { "$sum": 1 }
        }},
        // Sorting pipeline
        { "$sort": { "recommendCount": -1 } },
        // Optionally limit results
        { "$limit": 5 }
    ],
    function(err,result) {

       // Result is an array of documents
    }
);

So there are various pipeline operatorsthat can be used to $groupor $sortor $limitand other things as well. These can be presented in any order, and as many times as required. Just understanding that one "pipeline" stage flows results into the next to act on.

所以有各种管道操作符可以用于$group$sort$limit和其他东西。这些可以按任何顺序显示,并根据需要多次显示。只需理解一个“管道”阶段的结果就会进入下一个要采取行动的阶段。