SyntaxStudy
Sign Up
MongoDB Beginner 1 min read

Update Operations

MongoDB offers updateOne(), updateMany(), and replaceOne() for modifying existing documents. Update operations use update operators rather than passing a plain document — the most common are $set to change specific fields, $unset to remove fields, $inc to increment a numeric value, $push to append to an array, and $pull to remove matching elements from an array. The upsert option instructs MongoDB to insert a new document if no match is found, which is very useful for idempotent writes. replaceOne() replaces the entire document except the _id, while the $set-based updates only touch the specified fields, leaving everything else intact.
Example
// $set — update specific fields only
await db.collection('users').updateOne(
  { email: "carol@example.com" },
  { $set: { age: 29, updatedAt: new Date() } }
)

// $inc — increment a counter atomically
await db.collection('products').updateOne(
  { name: "Keyboard" },
  { $inc: { stock: -1, soldCount: 1 } }
)

// $push — append to an array
await db.collection('users').updateOne(
  { email: "carol@example.com" },
  { $push: { hobbies: "photography" } }
)

// $pull — remove a value from an array
await db.collection('users').updateOne(
  { email: "carol@example.com" },
  { $pull: { hobbies: "cycling" } }
)

// updateMany — update all matching documents
await db.collection('products').updateMany(
  { stock: { $lt: 10 } },
  { $set: { lowStock: true } }
)

// upsert — insert if not found
await db.collection('sessions').updateOne(
  { sessionId: "abc123" },
  { $set: { userId: "u1", lastSeen: new Date() } },
  { upsert: true }
)