MongoDB allows you to update documents using methods like updateOne(), updateMany(), and replaceOne(). You can also use a variety of update operators like $set, $inc, and $unset to control how data is changed.
Updates the first document that matches the filter.
db.users.updateOne(
{ name: "John" },
{ $set: { age: 30 } }
)
Updates all documents that match the filter.
db.users.updateMany(
{ status: "inactive" },
{ $set: { status: "active" } }
)
Replaces an entire document with a new one.
db.users.replaceOne(
{ name: "Alice" },
{ name: "Alice", age: 25, city: "Delhi" }
)
$set – Set the value of a field$inc – Increment a field by a value$unset – Remove a field from the document$rename – Rename a field$mul – Multiply the value of a field$min / $max – Only update if value is less/greater
db.products.updateOne(
{ name: "Laptop" },
{
$inc: { stock: -1 },
$unset: { discount: "" }
}
)
$set unless you're using replaceOne(). Omitting them may overwrite the entire document.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!