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?
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"
}
}
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With