MongoDB Exercise - Find the count of restaurants for each cuisine and borough
Write a MongoDB query to find the count of restaurants for each cuisine and 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([{
$group: {
_id: {
cuisine: "$cuisine",
borough: "$borough"
},
count: {
$sum: 1
}
}
}])
Output:
{ _id: { cuisine: 'Indian', borough: 'Manhattan' }, count: 26 }, {_id: { cuisine: 'Latin (Cuban, Dominican, Puerto Rican, South & Central American)', borough: 'Bronx' }, count: 21 }, { _id: { cuisine: 'Jewish/Kosher', borough: 'Manhattan' }, count: 14 }, { _id: { cuisine: 'Indonesian', borough: 'Brooklyn' }, count: 1 }, { _id: { cuisine: 'Bagels/Pretzels', borough: 'Brooklyn' }, count: 4 }, { _id: { cuisine: 'Juice, Smoothies, Fruit Salads', borough: 'Queens' }, count: 1 }, { _id: { cuisine: 'French', borough: 'Manhattan' }, count: 68 }, { _id: { cuisine: 'Korean', borough: 'Brooklyn' }, count: 1 }, { _id: { cuisine: 'Continental', borough: 'Manhattan' }, count: 4 }, { _id: { cuisine: 'Pizza/Italian', borough: 'Bronx' }, count: 8 }, .....
Explanation:
The provided query in MongoDB returns a list of documents, each representing a cuisine and borough combination and the count of restaurants in that combination.
The $group stage of the aggregation pipeline creates a new document for each distinct combination of cuisine and borough values and calculates the count of restaurants in that combination using the $sum accumulator operator.
The resulting documents have two fields: _id and count. The _id field contains an object with the distinct values of the cuisine and borough fields for each group, and the count field contains the count of restaurants in that cuisine and borough combination.
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.
Next: Find the count of restaurants received grade 'A' for each cuisine.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/mongodb-exercises/mongodb-exercise-56.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics