w3resource

MongoDB Exercise - Determine which borough has the most restaurants scoring 90 or higher and receiving an "A"


Write a MongoDB query to find the borough with the highest number of restaurants that have a grade of "A" and a score greater than or equal to 90.

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([
  {
    $match: {
      "grades.grade": "A",
      "grades.score": { $gte: 90 }
    }
  },
  {
    $group: {
      _id: "$borough",
count: { $sum: 1 }
    }
  },
  {
    $sort: { count: -1 }
  },
  {
    $limit: 1
  }
]);

Output:

[ { _id: 'Manhattan', count: 3 } ]

Explanation:

The code provided in MongoDB that finds the borough with the highest number of restaurants that have a grade of "A" and a score greater than or equal to 90.

The first stage of the aggregation $match which filters the documents based on the conditions -

checks whether the restaurant has a grade of "A" and it has a score greater than or equal to 90.

The $group stage, groups the matching documents by borough and counts the number of documents in each group.

The stage $sort, which sorts the results by the count field in descending order.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: Each borough's top 5 restaurants with the most "A" grades.
Next: MongoDB Query Exercises and Solution

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