MongoDB Update
Modify existing documents in your collections
✏️ Updating Documents
Updating documents in MongoDB means modifying existing data in collections. Use updateOne() to change a single document or updateMany() to modify multiple documents at once using update operators efficiently.
// Update one document
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)
// Update multiple documents
db.users.updateMany(
{ city: "Boston" },
{ $set: { country: "USA" } }
)
Update Methods
MongoDB provides several methods to update documents. Each method uses update operators to specify how fields should be modified, making updates precise and efficient.
updateOne()
Update first matching document
updateOne(filter, update)
updateMany()
Update all matching documents
updateMany(filter, update)
replaceOne()
Replace entire document
replaceOne(filter, doc)
Update Operators
$set, $inc, $push, $pull, etc.
{ $set: { field: value } }
🔹 Update One Document
Use updateOne() to modify the first document that matches your filter:
// Update user's age
db.users.updateOne(
{ name: "Alice" }, // Filter
{ $set: { age: 26 } } // Update
)
// Update with multiple fields
db.users.updateOne(
{ _id: 1 },
{
$set: {
age: 27,
city: "Boston",
lastUpdated: new Date()
}
}
)
Output:
✓ 1 document updated
matchedCount: 1, modifiedCount: 1
🔹 Update Many Documents
Use updateMany() to modify all documents matching your filter:
// Update all users in Boston
db.users.updateMany(
{ city: "Boston" },
{ $set: { country: "USA" } }
)
// Increase all product prices by 10%
db.products.updateMany(
{ category: "Electronics" },
{ $mul: { price: 1.1 } }
)
// Add field to all documents
db.orders.updateMany(
{},
{ $set: { status: "pending" } }
)
Output:
✓ 45 documents updated
matchedCount: 45, modifiedCount: 45
🔹 Common Update Operators
MongoDB provides operators to modify documents in different ways:
Field Update Operators:
- $set: Set field value
- $unset: Remove field
- $inc: Increment numeric value
- $mul: Multiply numeric value
- $rename: Rename field
- $currentDate: Set to current date
// Set field
db.users.updateOne(
{ name: "Bob" },
{ $set: { email: "[email protected]" } }
)
// Increment value
db.products.updateOne(
{ _id: 1 },
{ $inc: { stock: 10 } }
)
// Remove field
db.users.updateOne(
{ name: "Carol" },
{ $unset: { tempField: "" } }
)
// Set current date
db.orders.updateOne(
{ _id: 100 },
{ $currentDate: { lastModified: true } }
)
🔹 Array Update Operators
Special operators for updating arrays within documents:
// Add item to array
db.users.updateOne(
{ name: "Alice" },
{ $push: { hobbies: "reading" } }
)
// Add multiple items
db.users.updateOne(
{ name: "Bob" },
{ $push: {
hobbies: {
$each: ["gaming", "cooking"]
}
}}
)
// Remove item from array
db.users.updateOne(
{ name: "Carol" },
{ $pull: { hobbies: "swimming" } }
)
// Add only if not exists
db.users.updateOne(
{ name: "David" },
{ $addToSet: { tags: "premium" } }
)
Output:
Before: { hobbies: ["sports"] }
After: { hobbies: ["sports", "reading"] }
🔹 Replace One Document
Replace an entire document while keeping the same _id:
// Replace entire document
db.users.replaceOne(
{ name: "Alice" },
{
name: "Alice Smith",
age: 26,
email: "[email protected]",
city: "Boston"
}
)
// Note: _id remains the same, all other fields replaced
Output:
✓ Document replaced
matchedCount: 1, modifiedCount: 1
Warning:
replaceOne() removes all existing fields except _id. Use updateOne() with $set if you want to keep other fields.
🔹 Upsert Option
Insert a document if no match is found:
// Update or insert if not exists
db.users.updateOne(
{ email: "[email protected]" },
{
$set: {
name: "New User",
age: 25
}
},
{ upsert: true } // Insert if not found
)
// Upsert with multiple documents
db.products.updateMany(
{ category: "Books" },
{ $set: { discount: 10 } },
{ upsert: true }
)
Output:
✓ Document inserted (upsert)
upsertedId: ObjectId("...")
🔹 Update with Conditions
Use query operators in your filter for precise updates:
// Update products under $100
db.products.updateMany(
{ price: { $lt: 100 } },
{ $set: { onSale: true } }
)
// Update users over 30 in specific city
db.users.updateMany(
{
age: { $gt: 30 },
city: "New York"
},
{ $set: { category: "senior" } }
)
// Update with OR condition
db.orders.updateMany(
{
$or: [
{ status: "pending" },
{ status: "processing" }
]
},
{ $set: { priority: "high" } }
)
🔹 Complete Example
Here's a practical example of various update operations:
// Switch to database
use shopDB
// Update single product price
db.products.updateOne(
{ name: "Laptop" },
{ $set: { price: 899 } }
)
// Increase stock for all electronics
db.products.updateMany(
{ category: "Electronics" },
{ $inc: { stock: 50 } }
)
// Add review to product
db.products.updateOne(
{ _id: 1 },
{
$push: {
reviews: {
user: "John",
rating: 5,
comment: "Great product!"
}
}
}
)
// Update or create user profile
db.users.updateOne(
{ email: "[email protected]" },
{
$set: {
name: "Jane Doe",
lastLogin: new Date()
},
$inc: { loginCount: 1 }
},
{ upsert: true }
)
// Mark old orders as archived
db.orders.updateMany(
{
orderDate: { $lt: new Date("2024-01-01") }
},
{
$set: {
archived: true,
archivedDate: new Date()
}
}
)
// Verify updates
db.products.find({ category: "Electronics" }).count()
db.users.findOne({ email: "[email protected]" })
Output:
✓ Product price updated
✓ 23 products stock increased
✓ Review added
✓ User profile updated
✓ 156 orders archived