0

I have a MongoDB schema for blog posts that looks like:

{
  title: String,
  date: Date,
  description: String,
  tags: [String]
}

So, for example, a given blog post might have a document that looks like:

{
  title: 'My blog post about MongoDB',
  date: '2020-07-06T07:00:00.000+00:00',
  description: 'A blog about Mongo',
  tags: ['MongoDB', 'Javascript']
}

I'm trying to implement a query across my db that returns a mapping of each tag and a count of how many times that tag appears in the collection. So, for example if my collection has three posts (A, B, and C), where:

  • A.tags = ['MongoDB', 'Random']
  • B.tags = ['MongoDB', 'React']
  • C.tags = ['Nature', 'Random']

The query would return:

[
   { 'MongoDB', 2 },
   { 'Random', 2 },
   { 'React', 1 },
   { 'Nature', 1 },
   { 'Coding', 1 },
]

Is there a way to do so using some sort of aggregation pipeline or something similar?

Thanks!

JJ7907
  • 45
  • 1
  • 5

1 Answers1

1

Yes it's possible

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

PS: result format will be different but it will give the correct result you wanted

harshit kohli
  • 302
  • 2
  • 8
  • that's exactly the same what's given in link above, Please do not add answers for duplicate questions unless OP gets back asking for more help ! It just make redundant questions, try to mark questions as duplicates.. – whoami - fakeFaceTrueSoul Jun 12 '20 at 20:04
  • @whoami i somehow missed your comment! otherwise i would have done the same! – harshit kohli Jun 12 '20 at 21:09