MongoDB Exercise - Choose the restaurant with the highest average score for "Turkish" cuisine
Write a MongoDB query to find the restaurant that has the highest average score for thecuisine "Turkish".
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([
{ $match: { cuisine: "Turkish" } },
{ $unwind: "$grades" },
{ $group: {
_id: "$name",
avgScore: { $avg: "$grades.score" }
}},
{ $sort: { avgScore: -1 } }
])
Output:
{ _id: 'Turkish Cuisine', avgScore: 13.6 }, { _id: 'Memo Shish Kebab', avgScore: 13.5 }, { _id: 'Uskudar Restaurant', avgScore: 12 }, { _id: 'Turkuaz Turkish Cuisine', avgScore: 11.75 }, { _id: 'Saharas Turkish Cuisine', avgScore: 11.4 }, { _id: 'Pasha Turkish Restaurant', avgScore: 10.8 }, { _id: 'The Country Cafe', avgScore: 10.5 }, { _id: 'Istanbul Restaurant', avgScore: 10.5 }, { _id: 'Sahara Restaurant', avgScore: 10.285714285714286 }, { _id: 'Kebab House', avgScore: 10 }, { _id: 'Turkish Kitchen', avgScore: 7.666666666666667 }
Explanation:
The said query in MongoDB that returns a list of restaurants with name and the average score that serve Turkish cuisine, sorted in descending order by their average score. The output includes the name of the restaurant and the average score.
The $match stage filters the documents to only those that have the cuisine type "Turkish".
The $unwind stage deconstructs the grades array in each document into separate documents, one for each element of the array.
The $group stage groups the documents by the name field and calculates the average score using the $avg operator.
The $sort stage sorts the documents in descending order of the avgScore field.
Note: This output is generated using MongoDB server version 3.6
Improve this sample solution and post your code through Disqus.
Previous: Names and addresses of restaurants with a cuisine that starts with 'B'.
Next: Find the restaurants with the highest total score.
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://www.w3resource.com/mongodb-exercises/mongodb-exercise-81.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics