0

So I have data that looks like this:

{
   _id: 1, 
   ranking: 5, 
   tags: ['Good service', 'Clean room']
}

Each of these stand for a review. There can be multiple reviews with a ranking of 5. The tags field can be filled with up to 4 different tags.

4 tags are: 'Good service', 'Good food', 'Clean room', 'Need improvement'

I want to make a MongoDB aggregate query where I say 'for each ranking (1-5) give me the number of times each tag occurred for each ranking.

So an example result might look like this, _id being the ranking:

 [ 
   { _id: 5, 
    totalCount: 5, 
    tags: {
       goodService: 1, 
       goodFood: 3, 
       cleanRoom: 1, 
       needImprovement: 0
   }, 
   { _id: 4, 
    totalCount: 7, 
    tags: {
       goodService: 0, 
       goodFood: 2, 
       cleanRoom: 3, 
       needImprovement: 0
   }, 
   ...
]

Having trouble with the counting the occurrences of each tag. Any help would be appreciated

1 Answer 1

2

You can try below aggregation.

db.colname.aggregate([
  {"$unwind":"$tags"},
  {"$group":{
    "_id":{
      "ranking":"$ranking",
      "tags":"$tags"
    },
    "count":{"$sum":1}
  }},
  {"$group":{
    "_id":"$_id.ranking",
    "totalCount":{"$sum":"$count"},
    "tags":{"$push":{"tags":"$_id.tags","count":"$count"}}
  }}
])

To get the key value pair instead of array you can replace $push with $mergeObjects from 3.6 version.

"tags":{"$mergeObjects":{"$arrayToObject":[[["$_id.tags","$count"]]]}}
Sign up to request clarification or add additional context in comments.

6 Comments

So this works, except it's only bringing back the first of the rankings. I get the ranking for 1. The data looks reasonable. But I don't get info for 2,3,4 or 5.
Some of the reviews don't have tags. I might not have mentioned that
That is alright. I was able to get all rankings when I ran the query with multiple documents. Use {"$unwind":{path:"$tags", preservenullandemptyarrays:true}} to account for missing tags.
So almost there, the data is coming in. But I am also getting this error: "TypeError: Cannot read property 'tags' of undefined" I imagine this has to do with including the reviews with null ratgins. Can we get rid of that?
Giving you a point for the help so far. Thanks for sticking with me. I really appreciate it.
|

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.