i am trying to sort a simple array of objects but i am struggling with it. I read several post about how to do it and many of them recomend $unwind the array then $sort and then $group... but it is not working for me because after group i lose the "name" porpertie
Here is my document:
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : [
{
"type" : "exam",
"score" : 60.06045071030959
},
{
"type" : "quiz",
"score" : 52.79790691903873
},
{
"type" : "homework",
"score" : 71.76133439165544
},
{
"type" : "homework",
"score" : 34.85718117893772
}
]
}
I am trying this
{ $unwind: '$scores' },
{ $sort: { 'score': 1 } },
{
$group: {
_id: '$_id',
scores: { $push: '$scores' }
}
}
Expected output
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : [
{
"type" : "homework",
"score" : 71.76133439165544
},
{
"type" : "exam",
"score" : 60.06045071030959
},
{
"type" : "quiz",
"score" : 52.79790691903873
},
{
"type" : "homework",
"score" : 34.85718117893772
}
]
}
CodePudding user response:
Query
- your query with small changes and with the
$first
extra accumulator - all ids will have the same name, because they belonged to the first 1 document before the unwind, so we just take one (the first)
aggregate(
[{"$unwind": {"path": "$scores"}},
{"$sort": {"scores.score": -1}},
{"$group":
{"_id": "$_id",
"name": {"$first": "$name"},
"scores": {"$push": "$scores"}}}])