How to update data in a embedded child element in mongodb?

by arnoldo.moen , in category: MySQL , 4 months ago

How to update data in a embedded child element in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 4 months ago

@arnoldo.moen 

To update data in an embedded child element in MongoDB, you can use the dot notation in combination with the $set operator. Here's an example of how you can update the data in an embedded child element:


Suppose you have a collection called users with documents like this:

1
2
3
4
5
6
7
8
{
  "_id": 1,
  "name": "John Doe",
  "address": {
    "street": "123 Main Street",
    "city": "New York"
  }
}


To update the city in the address field for the user with _id 1, you can use the following update operation:

1
2
3
4
db.users.updateOne(
  { "_id": 1 },
  { "$set": { "address.city": "Los Angeles" } }
);


After running this operation, the document will be updated to:

1
2
3
4
5
6
7
8
{
  "_id": 1,
  "name": "John Doe",
  "address": {
    "street": "123 Main Street",
    "city": "Los Angeles"
  }
}


This is how you can update data in an embedded child element in MongoDB using the dot notation and the $set operator.

Related Threads:

How to update an embedded field in mongodb?
How to view an object embedded with a document in mongodb?
How to update data in MongoDB using PHP?
How to select all types of child element inside an svg using d3.js?
How to add new document in an embedded document in mongodb?
How to edit/update an element in xml file using php?