Script Valley
MongoDB: Complete Course
CRUD OperationsLesson 2.3

How to update documents in MongoDB with updateOne and updateMany

updateOne, updateMany, $set operator, $unset, $inc, $push, $pull, upsert option, replaceOne difference

Always use update operators

MongoDB $set update operator

MongoDB updates are surgical by default. The second argument to updateOne or updateMany must be an object containing update operators like $set. Passing a plain document without operators replaces the entire matched document — use replaceOne intentionally when that is what you want, not accidentally inside an update call.

// $set — add or overwrite specific fields, leave others untouched
await db.collection('products').updateOne(
  { name: 'Mouse' },
  { $set: { price: 34.99, updatedAt: new Date() } }
)

// $unset — remove a field from the document
await db.collection('products').updateOne(
  { name: 'Mouse' }, { $unset: { legacyCode: '' } }
)

// $inc — atomic server-side increment, safe under concurrency
await db.collection('products').updateOne(
  { name: 'Keyboard' }, { $inc: { stock: -1 } }
)

// $push — append an element to an array field
await db.collection('posts').updateOne(
  { _id: postId }, { $push: { tags: 'mongodb' } }
)

// $pull — remove elements matching a condition from an array
await db.collection('posts').updateOne(
  { _id: postId }, { $pull: { tags: 'draft' } }
)

updateMany and upsert

// Update all documents matching the filter
await db.collection('products').updateMany(
  { stock: 0 }, { $set: { discontinued: true } }
)

// upsert: insert if no match, update if found
await db.collection('settings').updateOne(
  { userId: 'u1' }, { $set: { theme: 'dark' } }, { upsert: true }
)

Up next

How to delete documents in MongoDB safely

Sign in to track progress