4

I have grouped data with favourites, and I have pushed into array.I want to sort the array with object key for example name,email,or age.

 {
                        $group:
                        {
                            _id: "$favourite",
                            favourite: { $first: "$favourite" },
                            data: {
                                $push: {
                                    "name": "$name",
                                    "email": "$email",
                                    "age": "$age"
                                }
                            }
                        }
                    }

I tried with this below code, but its not working.

  { "$sort": { "data.name": 1 } }

How to resolve this?

0

1 Answer 1

8

Use $sort before $group stage

db.collection.aggregate([
  { "$sort": { "name": 1 }},
  { "$group": {
    "_id": "$favourite",
    "favourite": { "$first": "$favourite" },
    "data": {
      "$push": {
        "name": "$name",
        "email": "$email",
        "age": "$age"
      }
    }
  }}
])
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.