w3resource

MongoDB Exercise - Find the count of restaurants in each borough


Write a MongoDB query to find the count of restaurants in 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([{
  $group: {
    _id: "$borough",
    count: {
      $sum: 1
    }
  }
}])

Output:

{ _id: 'Manhattan', count: 1883 },
{ _id: 'Bronx', count: 309 },
{ _id: 'Brooklyn', count: 684 },
{ _id: 'Staten Island', count: 158 },
{ _id: 'Queens', count: 738 }

Explanation:

The said query in MongoDB returns a list of documents have two fields: _id and count. The _id field contains the distinct value of the borough field for each group, and the count field contains the count of restaurants in that borough.

The $group stage of the aggregation pipeline creates a new document for each distinct value of borough and calculates the count of restaurants in that borough using the $sum accumulator 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 lowest score for each restaurant.
Next: Find the count of restaurants for each cuisine.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.