Lesson 7 of 18

Updating Documents

Update Operators

Use update operators to modify specific fields without replacing the entire document.

Example
// $set — set field values
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 29, city: "New York" } }
)

// $unset — remove a field
db.users.updateOne(
  { name: "Alice" },
  { $unset: { city: "" } }
)

// $inc — increment a number
db.products.updateOne(
  { name: "Laptop" },
  { $inc: { stock: -1 } }  // decrease by 1
)

// $push — add to array
db.users.updateOne(
  { name: "Alice" },
  { $push: { hobbies: "gaming" } }
)

Update Many & Replace

Update multiple documents at once or replace an entire document.

Example
// Update many documents
db.products.updateMany(
  { category: "Electronics" },
  { $set: { onSale: true } }
)

// Replace entire document
db.users.replaceOne(
  { name: "Bob" },
  { name: "Robert", email: "robert@example.com", age: 32 }
)

// Upsert — update or insert if not found
db.users.updateOne(
  { email: "new@example.com" },
  { $set: { name: "New User", age: 20 } },
  { upsert: true }
)