MongoDB Exercise - Find the count of restaurants for each cuisine
Write a MongoDB query to find the count of restaurants 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([{
$group: {
_id: "$cuisine",
count: {
$sum: 1
}
}
}])
Output:
{ _id: 'Mediterranean', count: 16 }, { _id: 'Chinese/Cuban', count: 5 }, { _id: 'Hamburgers', count: 159 }, { _id: 'Asian', count: 10 }, { _id: 'Café/Coffee/Tea', count: 1 }, { _id: 'Japanese', count: 80 }, { _id: 'Continental', count: 8 }, { _id: 'Other', count: 4 }, { _id: 'Indonesian', count: 2 }, { _id: 'Salads', count: 1 }, { _id: 'Bangladeshi', count: 1 }, { _id: 'Mexican', count: 73 }, { _id: 'French', count: 72 }, { _id: 'Filipino', count: 3 }, { _id: 'Greek', count: 25 }, .....
Explanation:
The given query in MongoDB returns a list of documents, each representing a cuisine and the count of restaurants in that cuisine.
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 using the $sum accumulator operator.
The resulting documents have two fields: _id and count. The _id field contains the distinct value of the cuisine field for each group, and the count field contains the count of restaurants in that cuisine.
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 in each borough.
Next: All restaurants with a score of 5 or higher.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics