0% completed
MongoDB allows for complex data structures by supporting embedded or nested documents. This feature is powerful for modeling real-world entities and their relationships directly within a single document. Querying these embedded documents requires a good understanding of MongoDB's querying capabilities.
In this lesson, we will explore how to query embedded or nested documents in MongoDB.
When querying embedded documents, you need to use dot notation to specify the field within the embedded document.
db.collection.find( { "embeddedField.subField": <value> } )
In the above syntax, embeddedField
is a parent document, and subField
is a nested document.
Inserting a Simple Embedded Document:
To insert the document into a MongoDB collection, you can use the insertOne()
method. Here’s how you can do it:
db.collection.insertOne({ name: "John Doe", address: { street: "123 Main St", city: "Anytown", zipcode: "12345" } })
Querying a Simple Embedded Document
To query documents where the city
in the address
is "Anytown":
db.users.find({ "address.city": "Anytown" })
This command retrieves all documents where the address.city
field is "Anytown".
Querying Multiple Fields in Embedded Documents
To query documents where the city
is "Anytown" and the zipcode
is "12345":
db.users.find({ "address.city": "Anytown", "address.zipcode": "12345" })
This command retrieves all documents where both the address.city
field is "Anytown" and the address.zipcode
field is "12345".
.....
.....
.....