J Seabolt
J Seabolt

Reputation: 2998

MongoDB aggregate query for values in an array

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

Upvotes: 0

Views: 252

Answers (1)

s7vr
s7vr

Reputation: 75984

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"]]]}}

Upvotes: 2

Related Questions