MongoDB Exercise - Names, addresses, and cuisine of restaurants with a cuisine that ends with the letter 'y'
Write a MongoDB query to find the name, address, and cuisine of the restaurants that have a cuisine that ends with the letter 'y'.
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: /y$/i } },
{ 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: '267', coord: [ -73.933605, 40.669476 ], street: 'Schenectady Avenue', zipcode: '11213' }, cuisine: 'Bakery', name: 'Tropical House Baking Co.' }, .....
Explanation:
The given query in MongoDB returns a list of restaurant documents whose cuisine ends with the letter "y", including the name, address, and cuisine fields, but excluding the "_id" field.
The pattern using the $regex operator, allows to match the regular expressions /y$/i against the "cuisine" field that matches any string that ends with the letter "y", regardless of case.
The resulting documents includes the "name", "address", and "cuisine" fields by set the values "1" and while the "0" value for "_id" indicates that it should be excluded.
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 cuisine that starts with 'B'.
Next: Find restaurants with cuisines that contain the word 'Pizza' and their addresses.
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-76.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics