0

I have following documents in my collection :

{
    "id" : 1,
    "tags" : ["tag1","tag2","tag3"]
},
{
    "id" : 2,
    "tags" : ["tag1","tag4","tag5"]
},
{
    "id" : 3,
    "tags" : ["tag1","tag5","tag6"]
},
...

I want to know how many times same array elements appears in the collection:

{
     "tag": "tag1",
     "count": 3
},
{
     "tag": "tag2",
     "count": 1
},
...

Is there a way to get this output in one aggregation?

Nisan Coşkun
  • 516
  • 7
  • 15

1 Answers1

1

you can use $unwind in a situation like this. here is the referene link.

db.getCollection('tests').aggregate([
    { $unwind: "$tags" },
    { $group: {
        _id: "$tags",
        count: { $sum: 1 }
    }}
])