w3resource

MongoDB Exercise - Find the count of restaurants received grade 'A' for each cuisine


Write a MongoDB query to find the count of restaurants that received a grade of 'A' for each cuisine.

Structure of 'restaurants' collection :

{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}

Query:

db.restaurants.aggregate([
  {
    $unwind: "$grades"
  },
  {
    $match: { "grades.grade": "A" }
  },
  {
    $group: {
      _id: "$cuisine",
count: { $sum: 1 }
    }
  }
])

Output:

{ _id: 'American ', count: 4938 },
{ _id: 'Chinese', count: 419 },
{ _id: 'Japanese', count: 280 },
{ _id: 'Indian', count: 166 },
  {
    _id: 'Bottled beverages, including water, sodas, juices, etc.',
count: 39
  },
{ _id: 'Mexican', count: 276 },
{ _id: 'Ethiopian', count: 11 },
{ _id: 'Pizza/Italian', count: 414 },
{ _id: 'German', count: 36 },
{ _id: 'Eastern European', count: 29 },
{ _id: 'Hotdogs', count: 15 },
{ _id: 'French', count: 283 },
{ _id: 'Thai', count: 50 },
{ _id: 'Vegetarian', count: 39 },
{ _id: 'Polish', count: 39 },
.....

Explanation:

The said query in MongoDB that returns a list of documents, each representing a cuisine and the count of restaurants in that cuisine that have a grade of 'A'.

The $unwind stage is used to "unwind" an array field grades in the restaurants collection. As a result, a separate document will be created for each grade in the restaurants collection.

The $match stage is used to filter the documents to only those that have a grade of 'A'.

The $group stage of the aggregation pipeline creates a new document for each distinct value of cuisine and calculates the count of restaurants in that cuisine that have a grade of 'A' using the $sum accumulator operator.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: Find the count of restaurants for each cuisine and borough.
Next: For each borough, find the number of restaurants with an 'A'.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.