1

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?

1 Answer 1

2

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
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.