Update Document
The MongoDB shell provides the following methods to update documents in a collection:
To update a single document, use
db.collection.updateOne().To update multiple documents, use
db.collection.updateMany().To replace a document, use
db.collection.replaceOne().
The examples on this page reference the Atlas sample dataset
Update Operator Syntax
To update a document, MongoDB provides update operators, such as $set, to modify field values.
Update a Single Document
Use the db.collection.updateOne() method to update the first document that matches a specified filter.
sample_mflix.movies collection where title equals "Tag":| use sample_mflix |
| db.movies.updateOne( { title: "Tag" }, |
| { |
| $set: { |
| plot: "One month every year, five highly competitive friends |
| hit the ground running for a no-holds-barred game of tag" |
| } |
| { $currentDate: { lastUpdated: true } } |
| }) |
The update operation:
Uses the
$setoperator to update the value of theplotfield for the movieTag.Uses the
$currentDateoperator to update the value of thelastUpdatedfield to the current date. IflastUpdatedfield does not exist,$currentDatewill create the field. See$currentDatefor details.
Update Multiple Documents
Use the db.collection.updateMany() to update all documents that match a specified filter.
sample_airbnb.listingsAndReviews collection to update where security_deposit is less than 100:| use sample_airbnb |
| db.listingsAndReviews.updateMany( |
| { security_deposit: { $lt: 100 } }, |
| { |
| $set: { security_deposit: 100, minimum_nights: 1 } |
| } |
| ) |
$set operator to update the value of the security_deposit field to 100 and the value of the minimum_nights field to 1.Replace a Document
To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne().
When replacing a document, the replacement document must contain only field/value pairs. Do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.
sample_analytics.accounts collection where account_id: 371138:| db.accounts.replaceOne( |
| { account_id: 371138 }, |
| { account_id: 893421, limit: 5000, products: [ "Investment", "Brokerage" ] } |
| ) |
| db.accounts.findOne( { account_id: 893421 } ) |