MongoDB Exercise - Find the cuisine type that is most likely to receive a "C" grade
Write a MongoDB query to find the cuisine type that is most likely to receive a 'C' grade.
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": "C"}},
{$group: {_id: "$cuisine", count: {$sum: 1}}},
{$sort: {count: -1}}
])
Output:
{ _id: 'American ', count: 172 }, { _id: 'Italian', count: 59 }, { _id: 'Pizza', count: 46 }, { _id: 'Latin (Cuban, Dominican, Puerto Rican, South & Central American)', count: 29 }, { _id: 'Chinese', count: 28 }, { _id: 'Japanese', count: 27 }, { _id: 'Pizza/Italian', count: 21 }, { _id: 'Caribbean', count: 19 }, { _id: 'Jewish/Kosher', count: 17 }, { _id: 'Mexican', count: 16 }, { _id: 'Bakery', count: 15 }, { _id: 'Hamburgers', count: 14 }, { _id: 'Indian', count: 11 }, { _id: 'Thai', count: 9 }, { _id: 'French', count: 8 }, { _id: 'Delicatessen', count: 7 }, { _id: 'Korean', count: 7 }, { _id: 'Café/Coffee/Tea', count: 7 }, { _id: 'Spanish', count: 6 }, { _id: 'Irish', count: 6 }, .....
Explanation:
The said query in MongoDB returns the count of "C" grades for each cuisine type in the restaurants collection.
The $unwind stage deconstructs the grades array in each document into separate documents, one for each element of the array.
The $match stage filters the documents to only include those with a "C" grade.
The $group stage groups the resulting documents by cuisine type and counts the number of documents for each cuisine type.
The $sort stage sorts the grouped documents in descending order by the count.
Note: This output is generated using MongoDB server version 3.6
Improve this sample solution and post your code through Disqus.
Previous: Get the names and addresses of restaurants with zipcodes starting with 10.
Next: Choose the restaurant with the highest average score for "Turkish" cuisine.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics