Let’s say I have the following data set:
test> db.test.insertMany([{_id: 'a', v: [2]}, {_id: 'b', v: [1, 3]}])
{ acknowledged: true, insertedIds: { '0': 'a', '1': 'b' } }
A regular query with sorting works as expected:
test> db.test.find().sort({v: 1})
[ { _id: 'b', v: [ 1, 3 ] }, { _id: 'a', v: [ 2 ] } ]
test> db.test.find().sort({v: -1})
[ { _id: 'b', v: [ 1, 3 ] }, { _id: 'a', v: [ 2 ] } ]
An aggregation pipeline with $sort
works the same way:
test> db.test.aggregate([{$sort: {v: 1}}])
[ { _id: 'b', v: [ 1, 3 ] }, { _id: 'a', v: [ 2 ] } ]
test> db.test.aggregate([{$sort: {v: -1}}])
[ { _id: 'b', v: [ 1, 3 ] }, { _id: 'a', v: [ 2 ] } ]
But when used with $group
by the same array field v
, sorting works differently:
test> db.test.aggregate([{$group: {_id: "$v"}}, {$sort: {_id: 1}}])
[ { _id: [ 1, 3 ] }, { _id: [ 2 ] } ]
test> db.test.aggregate([{$group: {_id: "$v"}}, {$sort: {_id: -1}}])
[ { _id: [ 2 ] }, { _id: [ 1, 3 ] } ]
Note that the last result is different.
I could not find anything in the documentation that would explain that behavior. Please help me understand it.