Update in MongoDB

Update Document

The MongoDB shell provides the following methods to update documents in a collection:

The examples on this page reference the Atlas sample dataset

To update a document, MongoDB provides update operators, such as $set, to modify field values.

Use the db.collection.updateOne() method to update the first document that matches a specified filter.

To update the first document in the 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 $set operator to update the value of the plot field for the movie Tag.

  • Uses the $currentDate operator to update the value of the lastUpdated field to the current date. If lastUpdated field does not exist, $currentDate will create the field. See $currentDate for details.

Use the db.collection.updateMany() to update all documents that match a specified filter.

To update all documents in the 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 }
}
)

he update operation uses the $set operator to update the value of the security_deposit field to 100 and the value of the minimum_nights field to 1.

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.

To replace the first document from the sample_analytics.accounts collection where account_id: 371138:

db.accounts.replaceOne(
{ account_id: 371138 },
{ account_id: 893421, limit: 5000, products: [ "Investment", "Brokerage" ] }
)


Run the following command to read your updated document:

db.accounts.findOne( { account_id: 893421 } )




Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form