w3resource

MongoDB Exercise - Find the highest score for each borough


Write a MongoDB query to find the highest score for each borough.

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: { borough: "$borough" },
highestScore: { $max: "$grades.score" } 
    } 
  }
])

Output:

{ _id: { borough: 'Bronx' }, highestScore: 76 },
{ _id: { borough: 'Manhattan' }, highestScore: 131 },
{ _id: { borough: 'Brooklyn' }, highestScore: 77 },
{ _id: { borough: 'Queens' }, highestScore: 66 },
{ _id: { borough: 'Staten Island' }, highestScore: 58 }

Explanation:

The given query in MongoDB that finds a list of documents which includes the fields borough and highestScore where each document represents the highest score for a particular borough.

The $unwind creates a separate document for each element in the grades array. Then the $group operator groups the documents by borough and find the highest score for each group using the $max aggregation operator.

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 borough.
Next: Find the lowest score for each borough.

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://w3resource.com/mongodb-exercises/mongodb-exercise-65.php