0

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

1 Answer 1

2

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 } },
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.