1 | initial version |
In MongoDB, you can update an object by using the update()
or updateOne()
method. To update an object with a specific key match, you can use the $set
operator in the update query. The $set
operator updates a particular field with a new value.
For example, if you have a collection named "users" with documents that look like this:
{
_id: ObjectId("1234567890"),
name: "John Doe",
age: 30,
email: "johndoe@example.com"
}
And you want to update the email address of the user with the name "John Doe", you can use the following code:
db.users.updateOne(
{ name: "John Doe" },
{ $set: { email: "newemail@example.com" } }
)
This query searches for a document with the name "John Doe" and updates the email field with the new value "newemail@example.com". If multiple documents match the query, only the first document will be updated. You can use update()
for updating multiple documents that match the query.