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

by cortez.connelly , in category: MySQL , 25 days ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 24 days 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": "[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".