Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb counting array combinations

I have this kind of documents

[
{
    ....
    tags : ["A","B"]
},
{
    ....
    tags : ["A","B"]
},
{
    ....
    tags : ["J","K"]
},
{
    ....
    tags : ["A","B","C"]
}
]

With the Aggregation Framwork I'd like to group by array combinations to have something like this :

[
    {
        _id:["A","B"],
        count : 2
    },
    {
        _id:["J","K"],
        count : 1
    },
    {
        _id:["A","B","C"],
        count : 1
    },
]

Is it possible to do that?

Thank you

like image 528
Fred Mériot Avatar asked Feb 04 '26 23:02

Fred Mériot


1 Answers

Not sure why you didn't even think this would work:

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

Returns:

{ "_id" : [ "A", "B", "C" ], "count" : 1 }
{ "_id" : [ "J", "K" ], "count" : 1 }
{ "_id" : [ "A", "B" ], "count" : 2 }

MongoDB "does not care" what you throw into the value of a "field" or "property". This applies to the "grouping key" of _id in the $group operator as well. Everything is a "document" and therefore a BSON value and is therefore valid.

Anything works. So long as it's what you want.

like image 107
Neil Lunn Avatar answered Feb 06 '26 14:02

Neil Lunn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!