You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
MongoDB provides three main methods for modifying existing documents: updateOne, updateMany, and replaceOne. All update operations take a filter (which documents to change) and an update specification (what to change).
updateOne modifies the first document that matches the filter.
db.users.updateOne(
{ email: "alice@example.com" },
{ $set: { age: 31, updatedAt: new Date() } }
)
The result tells you how many documents were matched and how many were actually modified.
updateMany modifies all documents matching the filter.
// Give all products with no category a default value
db.products.updateMany(
{ category: { $exists: false } },
{ $set: { category: "Uncategorised" } }
)
MongoDB's update operators let you make surgical changes without rewriting entire documents:
// $set — set field values
db.users.updateOne({ _id: id }, { $set: { name: "Bob" } })
// $unset — remove a field
db.users.updateOne({ _id: id }, { $unset: { legacyField: "" } })
// $inc — increment a numeric field
db.articles.updateOne({ _id: id }, { $inc: { "stats.views": 1 } })
// $push — append a value to an array
db.users.updateOne({ _id: id }, { $push: { hobbies: "painting" } })
// $pull — remove matching values from an array
db.users.updateOne({ _id: id }, { $pull: { hobbies: "cycling" } })
// $addToSet — add to array only if not already present
db.users.updateOne({ _id: id }, { $addToSet: { tags: "verified" } })
replaceOne replaces the entire document (except _id) with a new document. Use this when you want to swap out the full content rather than patch individual fields.
db.settings.replaceOne(
{ key: "theme" },
{ key: "theme", value: "dark", updatedAt: new Date() }
)
An upsert inserts a new document if no document matches the filter, or updates the existing one if it does. Enable it with { upsert: true }:
db.pageViews.updateOne(
{ page: "/home" },
{ $inc: { count: 1 } },
{ upsert: true }
)
findOneAndUpdate is useful when you need the document back after updating it. By default it returns the document before the update; pass { returnDocument: "after" } to get the updated version:
const updated = db.inventory.findOneAndUpdate(
{ sku: "ABC123" },
{ $inc: { qty: -1 } },
{ returnDocument: "after" }
)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.