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

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

问题描述

我在解决此mongodb(猫鼬)问题时遇到很多困难.

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

有一个推荐"模式(用户名,roomId,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

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天全站免登陆