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

by arnoldo.moen , in category: MySQL , a month ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a month 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.