在一个MongoDB聚合查询中进行排序和分组 [英] Sort and Group in one MongoDB aggregation query
问题描述
在一个聚合查询中使用$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屋!