w3resource

MongoDB Exercise - Find the highest score for each restaurant


Write a MongoDB query to find the highest 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",
      highest_score: {
        $max: "$grades.score"
      }
    }
  }
])

Output:

{ _id: 'Cucina Gourmet', highest_score: 17 },
{ _id: 'Picanteria El Botecito', highest_score: 13 },
{ _id: 'LefkosPygos Cafe', highest_score: 10 },
{ _id: 'Bull Head Tavern', highest_score: 11 },
{ _id: "Rosa'S Pizza", highest_score: 39 },
{ _id: 'Cafe Loup', highest_score: 19 },
{ _id: 'Cafe Rustico Ii', highest_score: 13 },
{ _id: 'Bliss Street Station Restaurant', highest_score: 12 },
{ _id: 'Hallmark Deli', highest_score: 10 },
{ _id: 'Starbucks Coffee (Store #7555)', highest_score: 13 },

.....

Explanation:

The $unwind operator deconstructs the grades array field of each document in the restaurants collection into multiple documents, one for each element in the array.

The $group operator groups the documents by the name field and calculates the maximum score in the grades array for each group. The result is returned as a new document with two fields: _id, which contains the value of the name field for the group, and highest_score, which contains the maximum score in the grades array for that group.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: Find the average score for each restaurant.
Next: Find the lowest score for each restaurant.

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