Using $project in MongoDB aggregate function to return certain data after $group

I am using MongoDB aggregate function and after $match and $group I have this array of data

[ { _id: { item: 'AAA' }, total: 66 },
{ _id: { item: 'BBB' }, total: 3 } ]

Is there any way to use $project to turn the final result into

[ {AAA: 66}, {BBB: 3} ]

And to make it more fun, let's say there is {CCC: 0} in the results as well, how can we filter and remove element CCC if it have value equal to 0?

Upvotes: 1

Views: 134

Answers (1)

Ashh
Ashh

Reputation: 46441

You can add below stages after your final $group stage

db.collection.aggregate([
  { "$group": {
    "_id": null,
    "data": {
      "$push": {
        "k": "$_id.item",
        "v": "$total"
      }
    }
  }},
  { "$replaceRoot": {
    "newRoot": {
      "$arrayToObject": "$data"
    }
  }}
])

Output

[
  {
    "AAA": 66,
    "BBB": 3
  }
]

Upvotes: 2

Related Questions