@cortez.connelly
To add a new document in an embedded document in MongoDB, you can use the $push operator along with the dot notation to specify the path to the embedded document.
Here is an example of how to add a new document to an embedded document in MongoDB:
For example, assuming you have a collection called users with the following document structure:
1 2 3 4 5 6 7 8 9 |
{
_id: ObjectId("123abc"),
name: "John Doe",
address: {
street: "123 Main St",
city: "New York",
country: "USA"
}
}
|
To add a new email address to the address embedded document for the user with _id "123abc", you can use the following update operation:
1 2 3 4 |
db.users.updateOne(
{ _id: ObjectId("123abc") },
{ $push: { "address.emails": "[email protected]" } }
)
|
This will add the new email address "[email protected]" to the emails field within the address embedded document for the user with _id "123abc".