MongoDB Exercise - Names and addresses of restaurants with a cuisine that starts with 'B'
Write a MongoDB query to find the name and address of the restaurants that have a cuisine that starts with the letter 'B'.
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(
{ "cuisine": { $regex: /^B/ } },
{ "name": 1,
"address": 1,
"cuisine" : 1,
"_id": 0 }
)
Output:
{ address: { building: '1007', coord: [ -73.856077, 40.848447 ], street: 'Morris Park Ave', zipcode: '10462' }, cuisine: 'Bakery', name: 'Morris Park Bake Shop' }, { address: { building: '120', coord: [ -73.9998042, 40.7251256 ], street: 'Prince Street', zipcode: '10012' }, cuisine: 'Bakery', name: "Olive'S" }, { address: { building: '7905', coord: [ -73.8740217, 40.7135015 ], street: 'Metropolitan Avenue', zipcode: '11379' }, cuisine: 'Bagels/Pretzels', name: 'Hot Bagels' }, .....
Explanation:
The said query in MongoDB that returns a list of documents containing the name, address, and cuisine of restaurants with a cuisine starting with the letter 'B'.
The $regex operator performs a regular expression search on the cuisine field starts with the letter 'B'.
The ^ character specifies that the pattern should match the start of the field's string value.
The argument of the find() method projection includes the name, address, and cuisine fields by setting their values to 1, and exclude the _id field by setting its value to 0.
Note: This output is generated using MongoDB server version 3.6
Improve this sample solution and post your code through Disqus.
Previous: Get the names and addresses of restaurants with zipcodes starting with 10.
Next: Names, addresses, and cuisine of restaurants with a cuisine that ends with the letter 'y'.
What is the difficulty level of this exercise?
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://www.w3resource.com/mongodb-exercises/mongodb-exercise-75.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics