猫鼬对聚合结果进行排序 [英] Mongoose sort the aggregated result

查看:29
本文介绍了猫鼬对聚合结果进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我需要获取最推荐的房间列表(按 roomId).以下是架构和我尝试过的猫鼬查询解决方案.

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

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

        }
    );

推荐答案

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

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

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

So there are various pipeline operators that can be used to $group or $sort or $limit and 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.

这篇关于猫鼬对聚合结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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