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!

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 i somehow missed your comment! otherwise i would have done the same!

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.