w3resource

MongoDB Exercise - Find the lowest score for each borough


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

Output:

{ _id: { borough: 'Manhattan' }, lowestScore: -1 },
{ _id: { borough: 'Queens' }, lowestScore: 0 },
{ _id: { borough: 'Staten Island' }, lowestScore: -1 },
{ _id: { borough: 'Bronx' }, lowestScore: 0 },
{ _id: { borough: 'Brooklyn' }, lowestScore: 0 }

Explanation:

The given query in MongoDB that finds a list of documents which includes the fields borough and lowestScore where each document represents the lowest 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 lowest score for each group using the $min 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 highest score for each borough.
Next: A list of restaurants with an 'A' on a specific date.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.