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?

0

1 Answer 1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.