w3resource

MongoDB Exercise - Find the highest score for each cuisine


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

Output:

{ _id: 'Delicatessen', maxScore: 57 },
{ _id: 'Café/Coffee/Tea', maxScore: 17 },
{ _id: 'Sandwiches/Salads/Mixed Buffet', maxScore: 25 },
{ _id: 'Thai', maxScore: 68 },
  {
    _id: 'Bottled beverages, including water, sodas, juices, etc.',
maxScore: 52
  },
{ _id: 'Caribbean', maxScore: 68 },
{ _id: 'Mexican', maxScore: 56 },
{ _id: 'Middle Eastern', maxScore: 54 },
{ _id: 'Russian', maxScore: 40 },
{ _id: 'French', maxScore: 48 },
{ _id: 'German', maxScore: 27 },
{ _id: 'Café/Coffee/Tea', maxScore: 56 },
{ _id: 'Chinese/Cuban', maxScore: 29 },
{ _id: 'Other', maxScore: 57 },
{ _id: 'Portuguese', maxScore: 26 },
{ _id: 'Tex-Mex', maxScore: 25 },
{ _id: 'Not Listed/Not Applicable', maxScore: 10 },
{ _id: 'Continental', maxScore: 51 },
{ _id: 'Chinese/Japanese', maxScore: 23 },
{ _id: 'Sandwiches', maxScore: 30 }
.....

Explanation:

The said query in MongoDB that provides a simple and efficient way to find the cuisine name, and maxScore as highest score for each cuisine in the restaurants collection.

The $unwind stage in aggregation pipeline is used to break down the grades array into individual documents.

The $group stage groups the documents by cuisine and use the $max operator to calculate the highest score 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 the average score for each cuisine.
Next: Find the lowest score for each cuisine.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.