How to update an embedded field in mongodb?

by darrion.kuhn , in category: MySQL , 5 months ago

How to update an embedded field in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 5 months ago

@darrion.kuhn 

To update an embedded field in MongoDB, you can use the $set operator along with dot notation to specify the nested field you want to update. Here's an example:


Assuming you have a collection named "users" with documents like this:


{ "_id": ObjectId("5f6e2dfd0eb9b2c08db3e48d"), "name": "John Doe", "address": { "street": "123 Main St", "city": "Los Angeles", "zipcode": "90001" } }


To update the "city" field in the "address" embedded document of a specific user, you can run the following update query in MongoDB:


db.users.updateOne( { "_id": ObjectId("5f6e2dfd0eb9b2c08db3e48d") }, { "$set": { "address.city": "New York" } )


This query will update the "city" field in the "address" embedded document of the user with the specified ID to "New York". Remember to replace the ObjectID value with the actual ID of the user you want to update.

Related Threads:

How to update data in a embedded child element in mongodb?
How to update field by multiply field value in mongodb?
How to update an already existing field in mongodb?
How to view an object embedded with a document in mongodb?
How to add new document in an embedded document in mongodb?
How to update value for multiple field in oracle sql?