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.