MongoDB Exercise - Find the average score for each restaurant
Write a MongoDB query to find the average score for each restaurant.
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"
},
{
$group: {
_id: "$name",
avgScore: {
$avg: "$grades.score"
}
}
}
])
Output:
{ _id: "Buddy'S Burrito & Taco Bar", avgScore: 13.333333333333334 }, { _id: 'Bergen Beach Cafe', avgScore: 12 }, { _id: 'Pergola Des Artistes', avgScore: 6.333333333333333 }, { _id: 'ZumStammtisch', avgScore: 12.833333333333334 }, { _id: 'Shubert Theater', avgScore: 10.4 }, { _id: "Big Daddy'S Diner", avgScore: 13.8 }, { _id: 'Strokos Gourmet Deli', avgScore: 12.8 }, { _id: 'Azusa Of Japan', avgScore: 11 }, { _id: 'Pax Wholesome Foods', avgScore: 6.875 }, { _id: "Erin'S Isle", avgScore: 9.5 }, .....
Explanation:
The said query in MongoDB makes an array of documents, representing a restaurant and its average score. The _id field of each document will contain the name of the restaurant, and the avgScore field will contain the calculated average score.
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 $group stage groups the documents by the name field and calculates the average score of all the grades for each restaurant using the $avg operator.
Note: This output is generated using MongoDB server version 3.6
Improve this sample solution and post your code through Disqus.
Previous: Find restaurants in Manhattan or Brooklyn that have at least one grade above 5.
Next: Find the highest score for each restaurant.
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-51.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics