MongoDB Exercise - A list of restaurants with an 'A' on a specific date
Write a MongoDB query to find the name and address of the restaurants that received a grade of 'A' on a specific date.
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.find(
{
"grades": {
"$elemMatch": {
"date": {
"$eq": ISODate("2013-07-22T00:00:00Z")
},
"grade": {
"$eq": "A"
}
}
}
},
{
"name": 1,
"address": 1,
"_id": 0
}
)
Output:
{
address: {
building: '351',
coord: [ -73.98513559999999, 40.7676919 ],
street: 'West 57 Street',
zipcode: '10019'
},
name: 'Dj Reynolds Pub And Restaurant'
},
{
address: {
building: '358',
coord: [ -73.963506, 40.758273 ],
street: 'East 57 Street',
zipcode: '10022'
},
name: "Neary'S Pub"
},
{
address: {
building: '22210',
coord: [ -73.759249, 40.761574 ],
street: 'Northern Boulevard',
zipcode: '11361'
},
name: 'Burger King'
},
.....
Explanation:
The said query in MongoDB retrieves the name and address fields of all documents from the 'restaurants' collection that have at least one "grades" sub-document containing a specific date and grade.
The "date": { "$eq": ISODate("2013-07-22T00:00:00Z") } condition checks within the $elemMatch operator if any of the grades have a date equal to 2013-07-22 and the "grade": { "$eq": "A" } condition checks if any of the grades have a grade equal to 'A'.
The date have used in the ISODate format which is similar to date in the restaurants collection.
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 borough.
Next: Names and addresses of restaurants with a grade of 'B' or 'C'.
What is the difficulty level of this exercise?
