0

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?

1 Answer 1

1

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

7 Comments

Wow it works. thank you so much. It is a little complicated for beginner :)
can you give me a good reference to exercise these things ?
no its very easy, $unwind looks scary at start, but its not, read mongodb documentation its very good
here its the reference with all the operators with examples, see the pipeline stage operators to find the $unwind
create a new question if you can, with sample data in, and expected data out. Seems like you will need $hour to get the hour from the date, and then group by tag + hour, 2 fields in group.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.