Help with two quick mongo queries

Hello, I am working on some HW, and I have issues with my two last queries.

Here you have my data fields (one example):
{“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”}

These are my questions:

  1. Return the list of boroughs ranked by the number of American restaurants in it. That is, for each borough, find how many restaurants serve American cuisine and print the borough and the number of such restaurants sorted by this number.

  2. Find the top 5 American restaurants in Manhattan that have the highest total score. Return for each restaurant the restaurants’ name and the total score.
    Hint: You can use “$unwind”.

While learning, it won’t give you any good to simply give you the straight answer. You won’t be learning.

For

you would need a $match for the appropriate cuisine.

For

and

a $group with a $sum will be helpful.

and to accomplish

obviously, it will be a $sort.

For

a $match on 2 fields is required. To get the

of a restaurant, despite the $unwind hint, a better and more efficient approach would be $reduce because its purpose is as documented

Applies an expression to each element in an array and combines them into a single value.

Thinks like

usually involve a $sort and $limit.

Thank you so much! This was very helpful!

1 Like