w3resource

MongoDB Exercise - Find the lowest score for each cuisine


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

Output:

{ _id: 'Middle Eastern', minScore: 2 },
{ _id: 'Jewish/Kosher', minScore: 0 },
{ _id: 'Hotdogs', minScore: 0 },
{ _id: 'Polish', minScore: 2 },
{ _id: 'Asian', minScore: 2 },
{ _id: 'Soul Food', minScore: 2 },
{ _id: 'Eastern European', minScore: 2 },
{ _id: 'Vegetarian', minScore: 5 },
{ _id: 'Czech', minScore: 8 },
{ _id: 'Spanish', minScore: 2 },
{ _id: 'Juice, Smoothies, Fruit Salads', minScore: 0 },
{ _id: 'Pancakes/Waffles', minScore: 3 },
  {
    _id: 'Latin (Cuban, Dominican, Puerto Rican, South & Central American)',
minScore: 0
  },
{ _id: 'Barbecue', minScore: 5 },
{ _id: 'Ice Cream, Gelato, Yogurt, Ices', minScore: 0 },
{ _id: 'Japanese', minScore: 0 },
{ _id: 'Indian', minScore: 0 },
{ _id: 'Bangladeshi', minScore: 7 },
{ _id: 'Donuts', minScore: 0 },
{ _id: 'Salads', minScore: 2 }
.....

Explanation:

The given query in MongoDB provides a simple and efficient way to find the _id, which is the cuisine name, and minScore as minimum score for each cuisine in the restaurants collection.

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

The $group grouped the documents by cuisine and use the $min operator to calculate the minimum 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 highest score for each cuisine.
Next: Find the average score for each borough.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.