Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

Update Documents

On this page

  • Update Documents in a Collection
  • Update a Document with MongoDB Atlas
  • Behavior

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.

  • MongoDB Compass.


Use the Select your language drop-down menu in the upper-right to set the language of the following examples.


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.

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:

1
  1. In the MongoDB Atlas UI, click Database in the sidebar.

  2. For the database deployment that contains the sample data, click Browse Collections.

  3. In the left navigation pane, select the sample_supplies database.

  4. Select the sales collection.

2

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.

3

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.

4

To confirm and save your changes, click the Update button.

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.

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.

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.

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.

←  Iterate a Cursor in the mongo ShellUpdates with Aggregation Pipeline →