在一个MongoDB聚合查询中进行排序和分组 [英] Sort and Group in one MongoDB aggregation query

查看:2557
本文介绍了在一个MongoDB聚合查询中进行排序和分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个聚合查询中使用$sort$group的行为异常.

Using $sort and $group in one aggregation query behaving strangely.

测试数据:

db.createCollection("test");

db.test.insert({
    ts : 100,
    category : 1
});

db.test.insert({
    ts : 80,
    category : 1
});

db.test.insert({
    ts : 60,
    category : 2
});

db.test.insert({
    ts : 40,
    category : 3
});

因此,当按ts对其进行排序时,一切看起来都不错,但是当我同时使用$sort$group时,结果顺序错误.查询:

So when sorting it by ts all looks good, but when I use both $sort and $group result goes in a wrong order. Query:

db.test.aggregate([
{
    $sort : {ts: 1}
},
{
    $group:{"_id":"$category"}
}
]);

结果相反:

{ "_id" : 1 }
{ "_id" : 2 }
{ "_id" : 3 }

是Mongo功能还是我的误解? Maby mongo首先应用分组,然后无法按缺席字段进行排序.因此,mongoose可能禁止在排序中使用区分.

Is it Mongo feature or my misunderstanding? Maby mongo firstly applied grouping and then can't sort by absent field. For this reason probably mongoose prohibits use distinct with sorting.

推荐答案

您需要先$group$sort结果.由于只需要_id字段,因此需要$project阶段.

You need to first $group and $sort the result. Since you only want the _id field you will need the $project stage.

db.test.aggregate(
    [
        { "$group": { "_id": "$category" }},
        { "$sort" : { "ts": 1 }},
        { "$project": { "_id": 1 }}
    ]
);

这篇关于在一个MongoDB聚合查询中进行排序和分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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