MongoDB Exercise - Find restaurants with cuisines that contain the word 'Pizza' and their addresses
Write a MongoDB query to find the name, address, and cuisine of the restaurants that have a cuisine that contains the word 'Pizza'.
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: /Pizza/i } },
{ name: 1, address: 1, cuisine: 1, _id: 0 }
)
Output:
{ address: { building: '464', coord: [ -73.9791458, 40.744328 ], street: '3 Avenue', zipcode: '10016' }, cuisine: 'Pizza', name: "Domino'S Pizza" }, { address: { building: '148', coord: [ -73.9806854, 40.7778589 ], street: 'West 72 Street', zipcode: '10023' }, cuisine: 'Pizza', name: "Domino'S Pizza" }, { address: { building: '156-71', coord: [ -73.840437, 40.6627235 ], street: 'Crossbay Boulevard', zipcode: '11414' }, cuisine: 'Pizza/Italian', name: 'New Park Pizzeria & Restaurant' }, .....
Explanation:
The query here in MongoDB returns a list of restaurant documents whose cuisine contains the word "Pizza", including the name, address, and cuisine fields, but excluding the "_id" field.
The pattern using the $regex operator, allows to match the regular expressions /Pizza/i, against the "cuisine" field that matches any string that contains the word "Pizza" 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, addresses, and cuisine of restaurants with a cuisine that ends with the letter 'y'.
Next: Find the restaurants achieved highest average score.
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://w3resource.com/mongodb-exercises/mongodb-exercise-77.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics