How To Update Document In MongoDB?

Rofl Facts
5 min readNov 24, 2023

You can update documents in MongoDB using the following methods:

The inventory collection is used in the examples on this page. Create the inventory collection after establishing a connection to a test database in your MongoDB instance:

await db.collection('inventory').insertMany([
{
item: 'canvas',
qty: 101,
size: { h: 22, w: 33.5, uom: 'cm' },
status: 'A'
},
{
item: 'journal',
qty: 23,
size: { h: 11, w: 22, uom: 'cm' },
status: 'A'
},
{
item: 'mat',
qty: 82,
size: { h: 21.4, w: 32.5, uom: 'cm' },
status: 'A'
},
{
item: 'mousepad',
qty: 23,
size: { h: 12, w: 21.85, uom: 'cm' },
status: 'P'
},
{
item: 'notebook',
qty: 20,
size: { h: 8.6, w: 10, uom: 'in' },
status: 'P'
},
{
item: 'paper',
qty: 101,
size: { h: 8.6, w: 10, uom: 'in' },
status: 'D'
},
{
item: 'planner',
qty: 71,
size: { h: 2.85, w: 3, uom: 'cm' },
status: 'D'
},
{
item: 'postcard',
qty: 44,
size: { h: 13, w: 5.25, uom: 'cm' },
status: 'A'
},
{
item: 'sketchbook',
qty: 81,
size: { h: 34, w: 22, uom: 'cm' },
status: 'A'
},
{
item: 'sketch pad',
qty: 93,
size: { h: 21.85, w: 33.5, uom: 'cm' },
status: 'A'
}
]);

Update Documents in a Collection

MongoDB has update operators like $set to change field values in a document.

Give an update document in the following format to the update methods in order to use the update operators:

{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}

If the field doesn’t already exist, some update operators, like $set, will create it. For more information, see the specific update operator reference.

Note: As of MongoDB 4.2, an aggregate pipeline may be used in place of an update document to define the changes that need to be made. For further information, see the method reference page.

Update a Single Document

The first document where item matches “paper” is updated in the following example by using the Collection.updateOne() function on the inventory collection:

await db.collection('inventory').updateOne(
{ item: 'paper' },
{
$set: { 'size.uom': 'cm', status: 'P' },
$currentDate: { lastModified: true }
}
);

The process of update operation:

  • updates the size’s value using the $set operator.Setting the value of the status field to “P” and the uom field to “cm”
  • updates the value of the lastModified column to the current date using the $currentDate operator. In the event that the lastModified column is absent, $currentDate will generate it. For more information, see $currentDate.

Update Multiple Documents

The example that follows updates all documents when quantity is less than 50 by using the Collection.updateMany() method on the inventory collection:

await db.collection('inventory').updateMany(
{ qty: { $lt: 50 } },
{
$set: { 'size.uom': 'in', status: 'P' },
$currentDate: { lastModified: true }
}
);

The process of update operation:

  • updates the size’s value using the $set operator.the value of the status field to “P” and the uom field to “in”,,
  • updates the value of the lastModified column to the current date using the $currentDate operator. In the event that the lastModified column is absent, $currentDate will generate it. For more information, see $currentDate.

Replace a Document

Pass a brand-new document to Collection as the second argument if you want to replace every word of a document with the exception of the _id field.replaceOne().

When a document needs to be replaced, it must only contain field/value pairs — that is, it cannot contain update operators expressions.

Fields from the original document may not be present in the new copy. Since the _id field is immutable, you can leave it out of the replacement document; but, if you do include it, its value must match the current value.

The first document from the inventory collection whose item is “paper” is replaced by the example that follows.

await db.collection('inventory').replaceOne(
{ item: 'paper' },
{
item: 'paper',
instock: [
{ warehouse: 'A', qty: 60 },
{ warehouse: 'B', qty: 40 }
]
}
);

Update a Document with MongoDB Atlas

Note: In the MongoDB Atlas UI, you can only edit a single document at a time. Connect to your Atlas deployment using mongosh or a MongoDB driver to update numerous documents or replace a single document. Then, follow the instructions on this page for your selected approach.

This section’s example makes use of the sample supply dataset. See Load Sample Data for instructions on how to load the sample dataset into your MongoDB Atlas setup.

The procedures below can be used to update a document in MongoDB Atlas:

1. Navigate to the collection.

a. In the sidebar of the MongoDB Atlas UI, select Database.

b. Click Browse Collections to view the database deployment containing the example data.

c. Choose the sample_supplies database from the navigation pane on the left.

d. Decide on the sales collection.

2. Specify a query filter document.

In the Filter box, you can define a query filter document. To define search parameters, a query filter document makes use of query operators.

Click Apply after pasting the query filter document into the Filter search bar:

{ saleDate: { $gte: { $date: "2016-01-01T00:00-00:00" }, $lte: { $date: "2016-01-02T00:00-00:00" } } }

All entries in the sample_supplies.sales collection whose saleDate falls on or between January 1 and 2, 2016 UTC time are returned by this query filter.

3. Edit a document.

Hover your cursor over a document in the query results to edit it by clicking the pencil icon. The document editor allows you to:

  • Include a new field.
  • Eliminate a field that already exists.
  • Modify the name, value, or type of a field.
  • Revert a particular modification.

For detailed instructions, see Create, View, Update, and Delete Documents.

4. Save your changes.

To verify and store your modifications, press the Update button.

Behavior

Atomicity

In MongoDB, every write action is atomic at the level of a single document. See Atomicity and Transactions for additional information about MongoDB and atomicity.

_id Field

After the _id field is set, it cannot be changed, and you cannot replace an existing document with a new one that has a different _id field value.

Field Order

MongoDB maintains the document field order during write operations, with the exception of the following scenarios:

  • The document’s first field is always the _id field.
  • Fields in the document may be rearranged as a result of updates that involve renaming field names.

Upsert Option

The action produces and inserts a new document if updateOne(), updateMany(), or replaceOne() include upsert: true in the options parameter document and no documents fit the given filter. The operation replaces or updates the matching document or documents if there are any.

See the individual reference pages for the procedures for further information on the newly created document.

Write Acknowledgement

You can set the level of acknowledgement that MongoDB is asked to provide for write operations by using write concerns. See Write Concern for more information.

--

--