When we are working with MongoDB databases, sometimes we’ll want to draw connections between multiple documents. MongoDB lets us embed documents directly within a parent document. These nested documents are known as sub-documents, and help us establish relationships between our data. For example, take a look at a single record from our auto_makers
collection:
{ maker: "Honda", country: "Japan", models: [ { name: "Accord" }, { name: "Civic" }, { name: "Pilot" }, … ] }, …
Notice how inside of this document, we have a field named models
that nests data about a maker’s specific model names. Here, we are establishing that the car maker "Honda"
has multiple models that are associated with it. We will touch on building relationships in our database a bit later in the course, but for now, we need to know how to query them! Once again, we can use the .find()
method to query these types of documents, by using dot notation (.
), to access the embedded field.
Let’s take a look at the syntax for querying on fields in embedded documents:
db.<collection>.find( { "<parent_field>.<embedded_field>": <value> } )
Note two important parts of the syntax:
- To query embedded documents, we must use a parent field (the name of the field wrapping the embedded document), followed by the dot (
.
) notation, and the embedded field we are looking for. - To query embedded documents, we must wrap the parent and embedded fields in quotation marks.
To see this in action, let’s return to our previous example of the auto_makers
collection:
{ maker: "Honda", country: "Japan", models: [ { name: "Accord" }, { name: "Civic" }, { name: "Pilot" }, … ] }, { maker: "Toyota", country: "Japan", models: [ { name: "4Runner" }, { name: "Corolla" }, { name: "Rav4" }, … ] }, { maker: "Ford", country: "USA", models: [ { name: "F-150" }, { name: "Bronco"}, { name: "Escape"}, … ] }
Notice, like we saw earlier, that the model
fields contain an array of embedded documents. If we wanted to find the document with "Pilot"
listed as a model, we would write the following command:
db.auto_makers.find({ "models.name" : "Pilot" })
This query would return the following document from our collection:
{ maker: "Honda", country: "Japan", models: [ { name: "Accord" }, { name: "Civic" }, { name: "Pilot" }, … ] }
Before moving on, let’s practice querying on fields in embedded documents!
Instructions
Let’s return to our restaurants
database. Switch to the database and query it to see all of the records inside the listingsAndReviews
collection. See if you can spot all of the embedded documents!
Notice that the restaurant listings in our collection have an embedded document called address
. We are in a rush and looking for a meal close to where we are visiting in Brooklyn, New York.
Query the listingsAndReviews
collection for restaurants where the zipcode
is 11231
.