0
0
MongodbHow-ToBeginner · 3 min read

How to Update Document in MongoDB: Syntax and Examples

To update a document in MongoDB, use the updateOne() or updateMany() methods with a filter and update operators like $set. For replacing an entire document, use replaceOne(). These methods modify documents matching the filter criteria.
📐

Syntax

The main methods to update documents in MongoDB are:

  • updateOne(filter, update, options): Updates the first document matching the filter.
  • updateMany(filter, update, options): Updates all documents matching the filter.
  • replaceOne(filter, replacement, options): Replaces the entire first document matching the filter.

The filter selects which documents to update. The update uses operators like $set to specify fields to change. options can control behavior like upsert.

mongodb
db.collection.updateOne(
  { <filter> },
  { $set: { <field1>: <value1>, ... } },
  { upsert: <boolean> }
)

// updateMany and replaceOne have similar syntax with their respective parameters
💻

Example

This example updates the age field of the first user named 'Alice' to 30.

mongodb
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 30 } }
)

// To update multiple users named 'Bob' to have active status true

// db.users.updateMany(
//   { name: "Bob" },
//   { $set: { active: true } }
// )
Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
⚠️

Common Pitfalls

Common mistakes when updating documents include:

  • Forgetting to use update operators like $set, which causes the entire document to be replaced.
  • Using updateOne when you want to update multiple documents.
  • Not specifying a filter, which can update unintended documents.
  • Confusing replaceOne with updateOne—the former replaces the whole document.
mongodb
/* Wrong: This replaces the whole document with only the age field */
db.users.updateOne(
  { name: "Alice" },
  { age: 30 }
)

/* Right: Use $set to update only the age field */
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 30 } }
)
📊

Quick Reference

MethodPurposeKey Parameters
updateOneUpdate first matching documentfilter, update, options
updateManyUpdate all matching documentsfilter, update, options
replaceOneReplace entire first matching documentfilter, replacement, options

Key Takeaways

Always use update operators like $set to modify specific fields without replacing the whole document.
Use updateOne to update a single document and updateMany to update multiple documents.
Specify a clear filter to target the correct documents for updating.
replaceOne replaces the entire document, so use it only when you want to overwrite all fields.
Check the update result to confirm how many documents were matched and modified.