Updating Documents
updateOne() and updateMany() change existing documents in place, and update operators like $set and $inc control exactly which fields change.
Setting a field with $set
JS mongosh
db.posts.updateOne(
{ title: "Hello, MongoDB" },
{ $set: { title: "Hello, MongoDB!" } }
)
Output
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}$set only touches the field you name — every other field on that document is left exactly as it was. This is the key difference from replaceOne(), a separate method that swaps out the entire document.
Incrementing a number with $inc
JS mongosh
db.posts.updateOne(
{ title: "Hello, MongoDB!" },
{ $inc: { views: 1 } }
)
Output
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }$inc adds the given amount to a numeric field in one atomic step — reading the current value, adding to it, and writing it back yourself would leave a window for a race condition under concurrent writes.
Updating many documents, and upserting
JS mongosh
db.posts.updateMany(
{ author: "Priya" },
{ $set: { featured: true } }
)
Output
{ acknowledged: true, insertedId: null, matchedCount: 2, modifiedCount: 2, upsertedCount: 0 }Adding { upsert: true } as a third argument tells MongoDB to insert a new document matching the filter if nothing matched — useful for "update if it exists, otherwise create it" logic in a single call.
Note: modern
updateOne()/updateMany() require an update operator like $set — passing a bare document ({ title: "New" } with no $set) throws an error rather than silently replacing the whole document. That's a real safety improvement over MongoDB's older API, where the equivalent mistake would have quietly wiped out every other field.