Get Started Free

How to update documents in MongoDB

Update one or many MongoDB documents with updateOne() and updateMany(): $set, $inc, $unset, and setting a field from another field. mongosh, Node, Python.

Updated November 22, 2026 ยท Tested on MongoDB 7.0, mongosh 2.9, Node driver 6.12, PyMongo 4.19

Quick Answer

Pass a filter and an update operator. updateOne changes the first match, updateMany changes all of them:

db.users.updateOne({ name: 'Ann' }, { $set: { status: 'active' } })
db.users.updateMany({ status: 'trial' }, { $set: { status: 'expired' } })

The second argument needs an operator such as $set. A plain object is rejected with "Update document requires atomic operators".

The update operators you will use most

OperatorDoesExample
$setSets a field, creating it if missing{ $set: { status: 'active', 'address.city': 'Paris' } }
$unsetRemoves a field{ $unset: { legacyId: '' } }
$incAdds to a number (negative to subtract){ $inc: { logins: 1, credits: -5 } }
$currentDateSets a field to the current date{ $currentDate: { updatedAt: true } }
$renameRenames a field{ $rename: { fullname: 'name' } }
$pushAppends to an array{ $push: { tags: 'vip' } }

You can combine operators in one update, as long as two of them don't touch the same field:

db.users.updateMany(
  { status: 'trial' },
  { $set: { status: 'expired' }, $currentDate: { updatedAt: true } }
)

In VisuaLeaf

Update documents in VisuaLeaf

For one value, click it in VisuaLeaf's Tree or Table View and type. Inputs are type-aware for dates, ObjectIds and Decimal128 and validate as you type, which guards against the type drift the findings above caught. Single edits go into the undo history.

For many documents, select rows in Table View, right-click and choose Batch Update. Pick the operation mode: All Documents, Selected Documents or Search Query. Then check the Query tab to see which documents will match, and write the change on the Update tab with $set, $unset, $inc, $push or $pull. Validate JSON catches syntax mistakes before you apply. A batch update can't be undone and clears the undo history, so the Query tab is your last check. See the Collection Activity docs.

VisuaLeaf Batch Update dialog with Operation Mode set to Selected Documents, a warning that the operation cannot be undone, Query and Update tabs, and Validate JSON, Cancel and Update buttons
Batch Update shows what will match before it changes anything.

Reading the result

{
  acknowledged: true,
  matchedCount: 3,    // documents the filter found
  modifiedCount: 2,   // documents that actually changed
  upsertedCount: 0
}

modifiedCount can be lower than matchedCount: MongoDB doesn't rewrite a document whose values already equal the new ones (more on exactly when below). A matchedCount of 0 means the filter matched nothing, which is the first thing to check when "the update did nothing". Common reasons are a string vs ObjectId mismatch on _id, or a typo in a field name.

What we found testing this

We checked exactly what counts as "modified" on MongoDB 7.0, starting from three documents where two already had s: 'a' and every n was the integer 1:

Updatematchedmodified
updateMany({}, { $set: { s: 'a' } })31
updateMany({}, { $inc: { n: 0 } })30
updateMany({}, { $unset: { missingField: '' } })30
updateOne({ _id: 1 }, { $setOnInsert: { q: 1 } })10
updateOne({ _id: 1 }, { $set: { n: NumberLong('1') } })11
  • A type change counts as a modification even when the number is equal. Setting the int 1 to NumberLong('1') reported modifiedCount: 1 and the stored type became long. This is how an "update that changes nothing" can still change how other queries and schema validation see the field.
  • $setOnInsert without upsert: true is silently ignored. No error, just modifiedCount: 0.
  • The "no operators" mistake fails differently per tool. mongosh and Node throw MongoInvalidArgumentError: Update document requires atomic operators. PyMongo raises a plain ValueError: update only works with $ operators before anything reaches the server, so a handler that only catches PyMongo errors won't see it.
  • Two operators on the same field are rejected outright: { $set: { s: 'x' }, $unset: { s: '' } } fails with Updating the path 's' would create a conflict at 's' and changes nothing.

Update all documents, or set a field from another field

An empty filter matches every document:

db.users.updateMany({}, { $inc: { logins: 1 } })

To compute a value from the document's own fields, pass an array as the update. That's an aggregation pipeline, so field paths like '$name' are read as values:

db.users.updateMany({}, [
  { $set: { label: { $concat: ['$name', '-', { $toString: '$logins' }] } } }
])

Without the square brackets, { $set: { label: '$name' } } sets label to the literal string "$name". It's an easy mistake to miss.

For updates that need real logic per document (loops, lookups, conditions), see bulk updates with mongosh scripts.

Get the updated document back, or replace it

// returns the document after the change (the default is before)
db.users.findOneAndUpdate(
  { name: 'Bo' },
  { $set: { vip: true } },
  { returnDocument: 'after' }
)

// replace the whole document except _id
db.users.replaceOne({ name: 'Cy' }, { name: 'Cy', status: 'active', logins: 0 })

Add { upsert: true } to updateOne or updateMany to insert a document when nothing matches. The filter's equality fields and the $set fields both end up in the new document.

From Node.js and Python

const users = client.db('app').collection('users')

const r = await users.updateMany({ status: 'trial' }, { $set: { status: 'expired' } })
console.log(r.matchedCount, r.modifiedCount)

const doc = await users.findOneAndUpdate(
  { name: 'Bo' }, { $set: { vip: true } }, { returnDocument: 'after' }
)
from pymongo import ReturnDocument

r = db.users.update_many({"status": "trial"}, {"$set": {"status": "expired"}})
print(r.matched_count, r.modified_count)

doc = db.users.find_one_and_update(
    {"name": "Bo"}, {"$set": {"vip": True}}, return_document=ReturnDocument.AFTER
)

Before you run a big update

  • Run the filter as a find first. db.users.countDocuments({ status: "trial" }) tells you how many documents you are about to change.
  • Index the filter field. updateMany on an unindexed field scans the whole collection and holds write locks longer.
  • Stop using update(). It's deprecated, and by default it updates only one document even when you meant all of them.

Frequently Asked Questions

What is the difference between updateOne and updateMany?

updateOne changes the first document that matches the filter. updateMany changes every matching document. Both take the same filter and update arguments.

Why does MongoDB say "Update document requires atomic operators"?

The update argument was a plain document. Wrap the fields in an operator, for example { $set: { status: "active" } }, or use replaceOne to replace the whole document.

Why is modifiedCount 0 when matchedCount is 1?

The document already had those values, so MongoDB did not rewrite it. The same happens for $inc by 0, $unset on a missing field, and $setOnInsert without upsert. Nothing is wrong.

How do I update a nested field?

Use dot notation inside $set, for example { $set: { "address.city": "Paris" } }. Setting { address: { city: "Paris" } } replaces the whole address object.

VisuaLeaf

Edit documents without hand-writing update operators

In VisuaLeaf you can edit, insert or delete documents directly in the collection view, and run mongosh scripts with visual output when an update needs code.