w3resource

MongoDB Exercise - Find the average score for each cuisine


Write a MongoDB query to find the average score 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([
  {
    $unwind: "$grades"
  },
  {
    $group: {
      _id: "$cuisine",
avgScore: { $avg: "$grades.score" }
    }
  }
])

Output:

_id: 'Korean', avgScore: 14.106194690265486 },
{ _id: 'Ethiopian', avgScore: 10 },
{ _id: 'Hamburgers', avgScore: 9.125854993160054 },
{ _id: 'Egyptian', avgScore: 12.727272727272727 },
{ _id: 'Soups & Sandwiches', avgScore: 8.394736842105264 },
{ _id: 'English', avgScore: 9.714285714285714 },
{ _id: 'Chicken', avgScore: 10.46 },
{ _id: 'Italian', avgScore: 12.212588310854207 },
{ _id: 'Pizza', avgScore: 11.489733840304183 },
{ _id: 'Steak', avgScore: 10.019607843137255 },
{ _id: 'Afghan', avgScore: 9.7 },
{ _id: 'Filipino', avgScore: 9.6875 },
.....

Explanation:

The said query in MongoDB provides a convenient way to calculate the average score for each cuisine in the restaurants collection.

The $unwind stage is used to break down the grades array and creates a separate document for each element in the grades array.

The $group stage is used to group the documents by the cuisine field and calculate the average score for each group. The $avg operator is used to calculate the average of the score field in the grades subdocument for each group.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: Find out how many restaurants have been graded in each month.
Next: Find the highest score for each cuisine.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-61.php