w3resource

MongoDB Exercise - Find out which restaurants have the word "coffee" in their names


Write a MongoDB query to find the name and address of the restaurants that have the word 'coffee' in their name.

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({ name: { $regex: /coffee/i } }, { name: 1, address: 1 })

Output:

{
    _id: ObjectId("6427d38d163a7d31d453f6e6"),
address: {
building: '26',
coord: [ -73.9983, 40.715051 ],
street: 'Pell Street',
zipcode: '10013'
    },
name: 'Mee Sum Coffee Shop'
  },
  {
    _id: ObjectId("6427d38d163a7d31d453f70c"),
address: {
building: '1191',
coord: [ -73.8513114, 40.8316981 ],
street: 'Castle Hill Avenue',
zipcode: '10462'
    },
name: "Lulu'S Coffee Shop"
  },
  {
    _id: ObjectId("6427d38d163a7d31d453f717"),
address: {
building: '10001',
coord: [ -74.03345, 40.612598 ],
street: '4 Avenue',
zipcode: '11209'
    },
name: 'Narrows Coffee Shop'
  },

.....

Explanation:

The given query in MongoDB that returns all documents in the restaurants collection where the name field contains the word 'coffee', and it will only include the name and address fields in the results.

The projection parameter specifies to include only the name and address fields, so set them to 1 and all other fields to 0.

The $regex operator performs a regular expression search on the name field which contains the word 'coffee'. The /i option makes the search case-insensitive.

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 grades of restaurants with at least one 'A' and no 'B' and ‘C’ grades.
Next: Get the names and addresses of restaurants with zipcodes starting with 10.

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-73.php