How to make a pipeline to group and count in mongodb?

Viewed 37

I have a document similar like this in mongodb with collection name: "movie" :-

collection = movie

[{
  "_id": {
    "$oid": "573a1390f29313caabcd446f"
  },

  "imdb": {
    "rating": 6.6,
    "votes": 1375,
    "id": 832
  },

 "review": {
    "rating": 6.6,
    "votes": 1375,
    "id": 832
  }

},

{
  "_id": {
    "$oid": "573a1390f29313caabcd45f7"
  },

  "imdb": {
    "rating": 4.6,
    "votes": 1375,
    "id": 832
  },

 "review": {
    "rating": 8,
    "votes": 432,
    "id": 322
  }

}]

How can I make a pipeline to group and count the number of based on the average of rating in review?

1 Answers

You can use $facet and $bucket for that:

db.movie.aggregate( [
  {
    $facet: {
      "review_rating": [
        {
            $bucket: {
                  groupBy: "$review.rating",                    
                  boundaries: [0, 3, 5, 10], // Boundaries for the buckets
                  default: "Other",                             // In case some data do not fall into a bucket
                  output: {                                     // Output for each bucket
                      "count": { $sum: 1 }
            }
        }
      }
      ],
      "imbd_rating": [
        {
            $bucket: {
                groupBy: "$imdb.rating",                    
                boundaries: [0, 3, 5, 10], // Boundaries for the buckets
                default: "Other",                             // In case some data do not fall into a bucket
                output: {                                     // Output for each bucket
                   "count": { $sum: 1 }
                }
            }
      }
      ]
    }
  }
])

That should count the number of elements of each bucket for both review.rating and imdb.rating. If you need more information, visit $facet in MongoDB Docs.

Related