1

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

Jaden Ng
  • 141
  • 1
  • 12
  • 1
    There actually is [`$reverseArray`](https://docs.mongodb.com/manual/reference/operator/aggregation/reverseArray/) but it basically depends on the array being in a set order before you even do that. The **sure** approach is to [`$sort`](https://docs.mongodb.com/manual/reference/operator/aggregation/sort/) **before** you actually [`$push`](https://docs.mongodb.com/manual/reference/operator/aggregation/push/) elements to a an array. Or of course [`$unwind`](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/) first as demonstrated on the existing answer. – Neil Lunn May 13 '19 at 08:53
  • db.col.aggregate( [ { $project: { "models.model": {"$reverseArray": "$models.model"} } }, ] ) This can reverse the array but it has duplication. "models" : [ { "model" : [ "abc003", "abc002", ] }, { "model" : [ "abc003", "abc002", ] } ] – Jaden Ng May 13 '19 at 09:22
  • 1
    Which is why you would instead `$unwind` and the `$group` on the the properties you want as "unique". Or possibly `$addToSet` depending 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. – Neil Lunn May 13 '19 at 09:25
  • @NeilLunn Ya thx for your comment trigger me that i can update by pushing the model to prepend at $position:0 so when i project query it is already in reverse order. – Jaden Ng May 13 '19 at 09:28
  • 1
    Usually the better idea to "update" in specified order. Doing a *pre-pend* is often enough, but you might also note the `$sort` modifier to `$push` as well. – Neil Lunn May 13 '19 at 09:30

0 Answers0