bor
bor

Reputation: 2351

Mongodb Find count of occurrence of all unique list elements

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.

Upvotes: 2

Views: 37

Answers (1)

mickl
mickl

Reputation: 49945

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

Upvotes: 1

Related Questions