w3resource

MongoDB Exercise - Find the restaurants achieved highest average score


Write a MongoDB query to find the restaurants achieved highest average score.

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: "$restaurant_id",
avgScore: {$avg: "$grades.score"}
  }},
  {$sort: {avgScore: -1}},
  {$limit: 1},
  {$project: {_id: 1, avgScore: 1}}
])

Output:

[ { _id: '40393488', avgScore: 38.6 } ]

Explanation:

The given query in MongoDB calculates the average score of each restaurant and returns only the restaurant with the highest average score, along with its restaurant_id and avgScore fields.

The $unwind stage that split each document of the grades array into multiple documents.

The $group operator grouped by the restaurant_id field, and a new field called avgScore is created using the $avg aggregation operator to calculate the average score of each restaurant.

The $sort then sorts the resulting documents in descending order by the avgScore field.

The $limit returns only the first document, meaning the restaurant with the highest average score.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: Find restaurants with cuisines that contain the word 'Pizza' and their addresses.
Next: Find those restaurants with the highest number of "A" grades.

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