Update Documents
You can update documents in MongoDB using the following methods:
Your programming language's driver.
The MongoDB Atlas UI. To learn more, see Update a Document with MongoDB Atlas.
➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.
Update Documents in a Collection
Note
Starting in MongoDB 4.2, MongoDB can accept an aggregation pipeline to specify the modifications to make instead of an update document. See the method reference page for details.
Update a Single Document
Update Multiple Documents
Replace a Document
Update a Document with MongoDB Atlas
Note
You can update only one document at a time in the MongoDB Atlas UI.
To update multiple documents or replace an entire document,
connect to your Atlas deployment from mongosh
or a MongoDB driver and follow the examples on this page
for your preferred method.
The example in this section uses the sample supplies dataset. To learn how to load the sample dataset into your MongoDB Atlas deployment, see Load Sample Data.
To update a document in MongoDB Atlas, follow these steps:
Specify a query filter document.
You can specify a query filter document in the Filter field. A query filter document uses query operators to specify search conditions.
Copy the following query filter document into the Filter search bar and click Apply:
{ saleDate: { $gte: { $date: "2016-01-01T00:00-00:00" }, $lte: { $date: "2016-01-02T00:00-00:00" } } }
This query filter returns all documents in the sample_supplies.sales
collection where saleDate
is on or between January 1 and 2, 2016
UTC time.
Edit a document.
To edit a document displayed in the query results, hover over the document and click on the pencil icon. In the document editor, you can:
Add a new field.
Delete an existing field.
Edit a field's name, value, or type.
Revert a specific change.
For detailed instructions, see Create, View, Update, and Delete Documents.
Behavior
Atomicity
All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions.
_id
Field
Once set, you cannot update the value of the _id
field nor can you
replace an existing document with a replacement document that has a
different _id
field value.
Field Order
For write operations, MongoDB preserves the order of the document fields except for the following cases:
The
_id
field is always the first field in the document.Updates that include
renaming
of field names may result in the reordering of fields in the document.
Upsert Option
Write Acknowledgement
With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.