在一个 MongoDB 聚合查询中进行排序和分组

2024-01-02

Using $sort and $group在一个行为奇怪的聚合查询中。

测试数据:

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 and $group结果顺序错误。询问:

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

结果按相反顺序排列:

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

是Mongo的特性还是我的误解? Maby mongo首先应用分组,然后无法按缺失字段排序。出于这个原因大概mongoose禁止使用不同的排序。


你需要先$group and $sort结果。既然你只想要_id您将需要的字段$project stage.

db.test.aggregate(
    [
        { "$group": { "_id": "$category" }},
        { "$sort" : { "ts": 1 }},
        { "$project": { "_id": 1 }}
    ]
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在一个 MongoDB 聚合查询中进行排序和分组 的相关文章

随机推荐