2

I have data like below in mongodb:

{
  "name":["apple", "banana", "oranges", "grapes"]
},
{
  "name":["apple", "banana"]
},
{
  "name":["apple", "oranges"]
},
{
  "name":["oranges", "banana"]
},
{
  "name":["grapes", "banana"]
}

I want to aggregate and get result as following:-

{
  "apple": 3,
  "banana":4,
  "grapes": 3,
  "oranges": 3
}

I tried something like this:-

db.collection.aggregate([
            {"$unwind": "$name" },
            {"$group": {"_id":  "$name", "count": { "$sum": 1 }}}
        ]]

This results in in accurate data, some of the unique elements get missed. Not sure what I did wrong.

1 Answer 1

1

You need another $group to merge all aggregates into single document and then run $arrayToObject on it. Additionally you can use $replaceRoot to promote new structure to root level:

db.collection.aggregate([
    {"$unwind": "$name" },
    { $group: { _id: "$name", count: { $sum: 1 } } },
    { $group: { _id: null, names: { $push: { k: "$_id", v: "$count" } } } },
    { $replaceRoot: { newRoot: { $arrayToObject: "$names" } } }
])

Mongo Playground

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.