How to add new document in an embedded document in mongodb?

by cortez.connelly , in category: MySQL , 3 months ago

How to add new document in an embedded document in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 3 months ago

@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:

  1. Connect to your MongoDB database and select the collection where the embedded document is stored.
  2. Use the updateOne or updateMany method to add a new document to the embedded document using the $push operator.


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": "john.doe@example.com" } }
)


This will add the new email address "john.doe@example.com" to the emails field within the address embedded document for the user with _id "123abc".

Related Threads:

How to view an object embedded with a document in mongodb?
When to create a new document in nosql?
What is considered as a document in mongodb?
How to cascade delete document in mongodb?
How to find a particular sub-document in mongodb?
How to update a whole document in mongodb using php?