w3resource

MongoDB Exercise - Name and address of restaurants with at least one 'A' and one 'B'


Write a MongoDB query to find the name and address of the restaurants that have at least one 'A' grade and one 'B' grade.

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({
  $and: [
{ "grades.grade": "A" },
{ "grades.grade": "B" }
  ]
},
{ name: 1, address: 1, _id: 0 })

Output:

{
address: {
building: '1269',
coord: [ -73.871194, 40.6730975 ],
street: 'Sutter Avenue',
zipcode: '11208'
    },
name: 'May May Kitchen'
  },
  {
address: {
building: '705',
coord: [ -73.9653967, 40.6064339 ],
street: 'Kings Highway',
zipcode: '11223'
    },
name: 'Seuda Foods'
  },
  {
address: {
building: '522',
coord: [ -73.95171, 40.767461 ],
street: 'East   74 Street',
zipcode: '10021'
    },
name: 'Glorious Food'

Explanation:

The said query in MongoDB returns a list of all the restaurant names and addresses that have at least one 'A' grade and one 'B' grade.

The $and operator combines the two conditions into a single query. The $elemMatch operator matchs any elements of the grades array that have a grade field equal to either "A" or "B".

The argument to the find() method specifies that the name field and the address field are to be included in the result, so for those fields, an inclusion value of 1 is assigned and the _id field has an exclusion value of 0.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: Names and addresses of restaurants with a grade of 'B' or 'C'.
Next: Names and addresses of restaurants with at least one 'A' and no 'B' grades.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.