MongoDB Exercise - Find the restaurant Id, name, and grades for those restaurants which achieved a specific grade, score on a specific date
Write a MongoDB query to find the restaurant Id, name, and grades for those restaurants which achieved a grade of "A" and scored 11 on an ISODate "2014-08-11T00:00:00Z" among many of survey dates.
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: ISODate("2014-08-11T00:00:00Z"),
grade: "A",
score: 11
}
}
},
{
restaurant_id: 1,
name: 1,
grades: 1
}
).pretty();
Output:
[
{
_id: ObjectId('677902d0a15eae4037064bb9'),
grades: [
{
date: ISODate('2014-08-11T00:00:00.000Z'),
grade: 'A',
score: 11
},
{
date: ISODate('2013-12-10T00:00:00.000Z'),
grade: 'A',
score: 9
},
{
date: ISODate('2013-06-10T00:00:00.000Z'),
grade: 'A',
score: 12
},
{
date: ISODate('2012-06-08T00:00:00.000Z'),
grade: 'A',
score: 13
},
{
date: ISODate('2012-01-25T00:00:00.000Z'),
grade: 'A',
score: 8
},
{
date: ISODate('2011-09-13T00:00:00.000Z'),
grade: 'A',
score: 12
}
],
name: 'Don Filippo Restaurant',
restaurant_id: '40372417'
}
]
Explanation:
The said query in MongoDB that searches for restaurants that received an "A" grade with a score of 11 on August 11th, 2014. The result documents will only include the "restaurant_id", "name", and "grades" fields.
The search criteria will match documents where the "grades" field contains an array of subdocuments, where at least one subdocument has a "date" field that matches the ISODate "2014-08-11T00:00:00Z".
The same subdocument also has a "grade" field that equals "A" and also has a "score" field that equals 11.
Improve this sample solution and post your code through Disqus.
Previous: Find the Id, name, borough, and cuisine of restaurants that don't prepare American or Chinese dishes or whose names begin with Wil.
Next: Id, name, and grades of restaurants with the 2nd element of grades array containing "A" and score 9 on ISODate "2014-08-11T00:00:00Z".
What is the difficulty level of this exercise?
