MongoDB Exercise - For each borough, find the number of restaurants with an 'A'
Write a MongoDB query to find the count of restaurants that received a grade of 'A' for each borough.
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: "$borough",
count: { $sum: 1 }
}
}
])
Output:
{ _id: 'Manhattan', count: 7447 }, { _id: 'Staten Island', count: 575 }, { _id: 'Queens', count: 2969 }, { _id: 'Brooklyn', count: 2651 }, { _id: 'Bronx', count: 1207 }
Explanation:
The said query in MongoDB that returns a list of documents, each representing a borough and the count of restaurants in that borough 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 that have a grade of 'A'. The $match stage uses the dot notation to access the grade field of the grades array field.
The $group stage of the pipeline creates a new document for each distinct value of borough and calculates the count of restaurants in that borough 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 received grade 'A' for each cuisine.
Next: Find the number of 'A'-rated restaurants by cuisine and borough.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics