Home > Back-end >  MongoDB group by elements in array
MongoDB group by elements in array

Time:11-11

I have a collection that looks like this:

{
  "id": "id1",
  "tags": ['a', 'b']
},
{
  "id": "id2",
  "tags": ['b', 'c']
},
{
  "id": "id3",
  "tags": ['a', 'c']
}

How can I make a query that groups by every element in the "tags" array, so the result looks like this?:

{'a': 2},
{'b': 2},
{'c': 2}

(where 2 is the number of times it appears, the count). Thanks for your help!

CodePudding user response:

You can use this aggregation query:

  • First $unwind the array to deconstruct an access like objects.
  • Then $group by tags and $sum 1 to get the total.
  • And last use $replaceRoot with $arrayToObject to get the desired output.
db.collection.aggregate([
  {
    "$unwind": "$tags"
  },
  {
    "$group": {
      "_id": "$tags",
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": [
          [
            {
              "k": "$_id",
              "v": "$count"
            }
          ]
        ]
      }
    }
  }
])

Example here

As an adittion, if you want to get sorted values (a, b, c...) you can add $sort stage like this example

  • Related