Updating Documents

View saved

Update one matching document

Always pair updates with a precise filter. $set changes fields without replacing the whole document.

db.books.updateOne(
  { title: "Practical MongoDB" },
  { $set: { year: 2025, featured: true } }
)

Update many

Touches every match. Preview with find first.

db.books.updateMany(
  { year: { $lt: 2020 } },
  { $set: { archive: true } }
)

Useful operators

  • $set / $unset — set or remove fields
  • $inc — increment numbers
  • $push / $pull — modify arrays
  • upsert: true — insert if nothing matches

Replace vs update

replaceOne swaps the entire document (except _id). Prefer update operators when changing a few fields.

db.books.replaceOne(
  { title: "Learn Indexes" },
  { title: "Learn Indexes", year: 2023, tags: ["index"] }
)

Comments

One comment per signed-in account. Comments are saved with this page’s URL.