Sort and group a MongoDB aggregation request

advertisements

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

Test data:

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

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

And the result in reverse order:

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

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.


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