w3resource

MongoDB Exercise - Names and addresses of restaurants with a grade of 'B' or 'C'


Write a MongoDB query to find the name and address of the restaurants that received a grade of 'B' or 'C' 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": ISODate("2013-04-05"), 
         "grade": { $in: [ "B", "C" ] } 
       } 
     } 
   },
   { 
     "name": 1, 
     "address": 1 
   }
)

Output:

{
    _id: ObjectId("6427d38d163a7d31d453fa5f"),
address: {
building: '1645',
coord: [ -73.9508638, 40.7826745 ],
street: 'Third Avenue',
zipcode: '10128'
    },
name: 'Corner Cafe And Bakery'
  },
  {
    _id: ObjectId("6427d38d163a7d31d453fdba"),
address: {
building: '4017',
coord: [ -74.00471689999999, 40.6501965 ],
street: '5 Avenue',
zipcode: '11232'
    },
name: 'Usuluteco Restaurant'
  },

.....

Explanation:

The said query in MongoDB that returns the documents that contains only the "name" and "address" fields of the matched documents.

The $elemMatch operator searches for an element in the "grades" array where both the "date" field is equal to the given date (2013-04-05) and the "grade" field is either "B" or "C". The $in operator is used to match either "B" or "C" in the "grade" field.

The date field is matched using the ISODate() function, which converts a date string to an ISODate object that can be compared with date objects of the collection restaurants.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: A list of restaurants with an 'A' on a specific date.
Next: Name and address of restaurants with at least one 'A' and one 'B'.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.