Updating Documents
Updating Documents
To update documents, the commands updateOne and updateMany can be used. The first command can be used to only find and update one document.
All the same parameters for finding a document to be updated can be used that were described above in the find section.
Setting Fields
For example to find a user with the username of user2 and to change that user's age to 65, we can use this $set operator to set fields to new values:
Example Output
Incrementing & Decrementing Values
We can also increment (or decrement by setting a negative number) fields by using the $inc operator:
Example Output
Removing (Unsetting) Fields
Fields can be removed from a document by using the $unsetoperator:
Example Output
Inserting Document If Not Exists
The additional upsert setting can be configured to automatically insert a document if it did not exist yet (false by default, so it will never create new a document if the editable document does not exist). It can be used like this:
db.users.updateOne({ username: "test3" }, {
$set: {
username: "test3",
age: 62
}
}, { upsert: true })
Example Output
Combining Operators
We can combine the the operators freely, like below, where we set both the password and increment the age: