Home > Blockchain >  Groupby Array elements in Mongodb Query
Groupby Array elements in Mongodb Query

Time:10-04

I have an array element in my DB and I want to group By and calculate the number of repetitions of different elements in this array. assume following collection:

{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   tags: ['SQL', 'database', 'NoSQL'],
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'NoSQL Overview', 
   tags: ['mongodb', 'database', 'PHP'],
}

I want to calculate the number of repetitions of different elements in tags field such as mongodb, database, noSQL in this collection. How can I solve this problem in mongo?

CodePudding user response:

Query

  • counts the repetitions in all the collection
  • unwind to make each tag in seperate document
  • group by tag, and count the repetitions

Test code here

db.collection.aggregate([
  {
    "$unwind": {
      "path": "$tags"
    }
  },
  {
    "$group": {
      "_id": "$tags",
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "tag": "$_id",
      "count": 1
    }
  }
])
  • Related