I would like to do aggregation by using $project to query array of objects to get single field data and store as array in descending order or reverse array. I had searched for some solutions at stackoverflow but did not see questions with project query then reverse array.
For example below is my mock data:
"models" : [
{
"model" : "abc002",
"total_modules" : 2
},
{
"model" : "abc003",
"total_modules" : 2
},
{
"model" : "abc004",
"total_modules" : 2
},
]
I have tried with the below solution but it is not exactly what I want as the output is slightly different as shown below:
db.collection.aggregate([
{$project: {"models.model":1}}
])
Output:
"models" : [
{
"model" : "abc002"
},
{
"model" : "abc003"
},
{
"model" : "abc004"
}
]
**In fact, I would like to get this output:**
{
models: [ abc004, abc003, abc002 ]
}
OR
{
models: [ {model:abc004}, {model:abc003}, {model:abc002} ]
}
$reverseArraybut it basically depends on the array being in a set order before you even do that. The sure approach is to$sortbefore you actually$pushelements to a an array. Or of course$unwindfirst as demonstrated on the existing answer.$unwindand the$groupon the the properties you want as "unique". Or possibly$addToSetdepending on your needs. What you have been basically pointed to "points out" that sorting an array ( as opposed to simply "reversing" ) needs the demonstrated process. Just as "grouping" is it's own process.$sortmodifier to$pushas well.