Beginner MongoDB

Updating Documents in MongoDB

Use updateOne(), updateMany(), and replaceOne() with update operators like $set, $inc, and $push.

6 min read Tutorial

Updating Documents

MongoDB provides several methods to modify existing documents. The most common are updateOne() and updateMany(), which use update operators to change specific fields without replacing the entire document.

updateOne()

Updates the first document that matches the filter. The second argument uses update operators to specify the changes:

// Set the status to "active" for a specific user
db.users.updateOne(
  { email: "alice@example.com" },
  { $set: { status: "active", updatedAt: new Date() } }
)

// Result:
// { matchedCount: 1, modifiedCount: 1 }

updateMany()

Updates all documents that match the filter. Use this for bulk modifications:

// Mark all products under $10 as "on_sale"
db.products.updateMany(
  { price: { $lt: 10 } },
  { $set: { onSale: true } }
)

// Increment the view count for all blog posts in a category
db.posts.updateMany(
  { category: "tech" },
  { $inc: { views: 1 } }
)

Common Update Operators

MongoDB offers a rich set of update operators for different modification needs:

// $set - Set field values
db.users.updateOne(
  { _id: userId },
  { $set: { name: "Alice Smith", role: "admin" } }
)

// $unset - Remove a field
db.users.updateOne(
  { _id: userId },
  { $unset: { temporaryToken: "" } }
)

// $inc - Increment a numeric value
db.products.updateOne(
  { _id: productId },
  { $inc: { stock: -1, soldCount: 1 } }
)

// $push - Add an element to an array
db.users.updateOne(
  { _id: userId },
  { $push: { tags: "premium" } }
)

// $pull - Remove elements from an array
db.users.updateOne(
  { _id: userId },
  { $pull: { tags: "trial" } }
)

replaceOne()

If you need to replace an entire document (except the _id field), use replaceOne():

db.users.replaceOne(
  { email: "alice@example.com" },
  {
    email: "alice@example.com",
    name: "Alice Smith",
    role: "admin",
    updatedAt: new Date()
  }
)

Upsert

Set upsert: true to insert a new document if no match is found:

db.settings.updateOne(
  { key: "theme" },
  { $set: { key: "theme", value: "dark" } },
  { upsert: true }
)

Key Takeaways

  • updateOne() modifies the first match; updateMany() modifies all matches.
  • Use operators like $set, $inc, and $push for targeted changes.
  • replaceOne() swaps the entire document body.
  • Enable upsert: true to insert when no document matches.

Try this query in UnifySQL

Write, optimize, and collaborate on MongoDB queries with AI assistance.

Start Free