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

5
  • 1
    There actually is $reverseArray but it basically depends on the array being in a set order before you even do that. The sure approach is to $sort before you actually $push elements to a an array. Or of course $unwind first as demonstrated on the existing answer. Commented May 13, 2019 at 8: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", ] } ] Commented May 13, 2019 at 9: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. Commented May 13, 2019 at 9: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. Commented May 13, 2019 at 9: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. Commented May 13, 2019 at 9:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.