Move the $sort
after $group
, since the previous sort will be lost after grouping.
db.orders.aggregate([{
"$unwind": "$items"
}, {
"$match": {}
}, {
"$group": {
"price": {
"$first": "$price"
},
"items": {
"$push": {
"sku": "$items.sku"
}
},
"_id": "$_id"
}
}, {
"$sort": {
"price": -1
}
}, {
"$project": {
"_id": 0,
"price": 1,
"items": 1
}
}])
For $natural
operator, this is the quoted from the doc.
The $natural operator uses the following syntax to return documents in the order they exist on disk
Long story short, that means the order you see is not necessarily consistent with the order it store in DB.