w3resource

MongoDB Exercise - Names and addresses of restaurants with at least one 'A' and no 'B' grades


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

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": { $not: { $eq: "B" } } }
  ]
},
{ name: 1, address: 1, _id: 0 })

Output:

{
address: {
building: '8825',
coord: [ -73.8803827, 40.7643124 ],
street: 'Astoria Boulevard',
zipcode: '11369'
    },
name: 'Brunos On The Boulevard'
  },
  {
address: {
building: '1839',
coord: [ -73.9482609, 40.6408271 ],
street: 'Nostrand Avenue',
zipcode: '11226'
    },
name: 'Taste The Tropics Ice Cream'
  },
  {
address: {
building: '351',
coord: [ -73.98513559999999, 40.7676919 ],
street: 'West   57 Street',
zipcode: '10019'
    },
name: 'Dj Reynolds Pub And Restaurant'
  },
.....


Explanation:

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

The $and operator combines the two conditions into a single query. The $elemMatch operator matches any elements of the grades array that have a grade field equal to "A" and the $not and $eq operators are used together to negate the condition for "B", so that it matches documents where there are no elements with "B".

The argument to the find() method are decide to include the fields name and address, so a value of 1 is included with these fields and used a value of 0 to exclude the _id field.

Note: This output is generated using MongoDB server version 3.6

Improve this sample solution and post your code through Disqus.

Previous: Name and address of restaurants with at least one 'A' and one 'B'.
Next: Names, addresses and grades of restaurants with at least one 'A' and no 'C' grades.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb-exercises/mongodb-exercise-70.php