Reputation: 199
Here is the example:
{_id: 111, sort: [{order:1}, {order:3}]}
{_id: 222, sort: [{order:2}, {order:5}]}
{_id: 333, sort: [{order:1}, {order:3}, {order:4}]}
I want to sort by sort.order from big to small, and get
{_id: 222, sort: {order:5}}
{_id: 333, sort: {order:4}}
{_id: 111, sort: {order:3}}
Upvotes: 0
Views: 211
Reputation: 49945
You need to $unwind them to determine which one has highest value and then group back to take only one:
db.col.aggregate([
{ $unwind: "$sort" },
{ $sort: { "sort.order": -1 } },
{
$group: {
_id: "$_id",
sort: { $first: "$sort" }
}
},
{ $sort: { "sort.order": -1 } },
])
Upvotes: 2