MongoDB Update
Master document modification and data updates in MongoDB
✏️ What is MongoDB Update?
Update operations in MongoDB allow you to modify existing documents in a collection. You can update single documents, multiple documents, or even insert new documents if they don't exist. MongoDB provides powerful update operators to modify specific fields, arrays, and nested objects efficiently.
// Basic update operations
db.users.updateOne(
{ name: "John" }, // Filter
{ $set: { age: 30 } } // Update
)
db.products.updateMany(
{ category: "electronics" }, // Filter multiple documents
{ $inc: { price: 10 } } // Increase price by 10
)
Update Methods
updateOne()
Update single document
db.users.updateOne(
{ _id: 1 },
{ $set: { status: "active" } }
)
updateMany()
Update multiple documents
db.products.updateMany(
{ price: { $lt: 100 } },
{ $set: { sale: true } }
)
replaceOne()
Replace entire document
db.users.replaceOne(
{ _id: 1 },
{ name: "John", age: 25 }
)
upsert
Update or insert if not exists
db.users.updateOne(
{ email: "[email protected]" },
{ $set: { name: "New User" } },
{ upsert: true }
)
Basic Update Operations
Learn the fundamental update methods in MongoDB
// Sample data
db.users.insertMany([
{ _id: 1, name: "Alice", age: 25, city: "New York" },
{ _id: 2, name: "Bob", age: 30, city: "London" },
{ _id: 3, name: "Charlie", age: 35, city: "Paris" }
])
// updateOne() - Updates the first matching document
db.users.updateOne(
{ name: "Alice" }, // Filter criteria
{ $set: { age: 26 } } // Update operation
)
// updateMany() - Updates all matching documents
db.users.updateMany(
{ age: { $gte: 30 } }, // Filter: age >= 30
{ $set: { status: "senior" } } // Update operation
)
// Check results
db.users.find().pretty()
Update Operators
MongoDB provides various operators to modify documents
🔹 Field Update Operators
// $set - Set field value
db.users.updateOne(
{ _id: 1 },
{ $set: { email: "[email protected]", verified: true } }
)
// $unset - Remove field
db.users.updateOne(
{ _id: 1 },
{ $unset: { city: "" } } // Removes the city field
)
// $inc - Increment numeric value
db.products.updateOne(
{ _id: 1 },
{ $inc: { price: 5, views: 1 } } // Increase price by 5, views by 1
)
// $mul - Multiply numeric value
db.products.updateOne(
{ _id: 1 },
{ $mul: { price: 1.1 } } // Increase price by 10%
)
// $rename - Rename field
db.users.updateMany(
{},
{ $rename: { "name": "fullName" } }
)
🔹 Array Update Operators
// Sample data with arrays
db.users.updateOne(
{ _id: 1 },
{ $set: { hobbies: ["reading", "swimming"], scores: [85, 90, 78] } }
)
// $push - Add element to array
db.users.updateOne(
{ _id: 1 },
{ $push: { hobbies: "cycling" } }
)
// $pull - Remove elements from array
db.users.updateOne(
{ _id: 1 },
{ $pull: { hobbies: "swimming" } }
)
// $addToSet - Add unique element to array
db.users.updateOne(
{ _id: 1 },
{ $addToSet: { hobbies: "reading" } } // Won't add duplicate
)
// $pop - Remove first (-1) or last (1) element
db.users.updateOne(
{ _id: 1 },
{ $pop: { scores: 1 } } // Remove last score
)
Advanced Update Operations
Complex update scenarios and techniques
🔹 Conditional Updates
// $min - Update if new value is smaller
db.products.updateOne(
{ _id: 1 },
{ $min: { price: 50 } } // Only update if 50 is less than current price
)
// $max - Update if new value is larger
db.users.updateOne(
{ _id: 1 },
{ $max: { highScore: 95 } } // Only update if 95 is greater than current
)
// $currentDate - Set current date
db.users.updateOne(
{ _id: 1 },
{ $currentDate: { lastModified: true, lastLogin: { $type: "date" } } }
)
🔹 Array Element Updates
// Update specific array element by position
db.users.updateOne(
{ _id: 1 },
{ $set: { "scores.0": 95 } } // Update first element
)
// Update array element using $ positional operator
db.users.updateOne(
{ _id: 1, scores: 78 },
{ $set: { "scores.$": 88 } } // Update the matched element (78 becomes 88)
)
// Update all array elements using $[]
db.users.updateOne(
{ _id: 1 },
{ $inc: { "scores.$[]": 5 } } // Add 5 to all scores
)
// Update array elements with condition using $[identifier]
db.users.updateOne(
{ _id: 1 },
{ $set: { "scores.$[element]": 100 } },
{ arrayFilters: [{ "element": { $gte: 90 } }] } // Set scores >= 90 to 100
)
Upsert Operations
Update existing documents or insert new ones if they don't exist
// Basic upsert - insert if document doesn't exist
db.users.updateOne(
{ email: "[email protected]" },
{
$set: {
name: "New User",
age: 25,
createdAt: new Date()
}
},
{ upsert: true } // Insert if no match found
)
// Upsert with $setOnInsert - only set these fields on insert
db.products.updateOne(
{ sku: "ABC123" },
{
$set: { price: 29.99, inStock: true },
$setOnInsert: {
createdAt: new Date(),
category: "electronics"
}
},
{ upsert: true }
)
// Check the result
var result = db.users.updateOne(
{ email: "[email protected]" },
{ $set: { lastLogin: new Date() } },
{ upsert: true }
)
if (result.upsertedId) {
print("New document created with ID: " + result.upsertedId)
} else {
print("Existing document updated")
}
Replace Operations
Replace entire documents while keeping the same _id
// replaceOne() - Replace entire document content
var originalDoc = db.users.findOne({ _id: 1 })
print("Original document:")
printjson(originalDoc)
// Replace with completely new document structure
db.users.replaceOne(
{ _id: 1 },
{
fullName: "Alice Johnson",
contact: {
email: "[email protected]",
phone: "123-456-7890"
},
preferences: {
theme: "dark",
notifications: true
},
updatedAt: new Date()
}
)
var newDoc = db.users.findOne({ _id: 1 })
print("Replaced document:")
printjson(newDoc)
// Note: _id remains the same, but all other fields are replaced
Update with Aggregation Pipeline
Use aggregation expressions in update operations
// Sample data
db.orders.insertMany([
{ _id: 1, items: [{ price: 10 }, { price: 20 }, { price: 15 }] },
{ _id: 2, items: [{ price: 25 }, { price: 30 }] }
])
// Calculate total using aggregation pipeline in update
db.orders.updateMany(
{},
[
{
$set: {
total: {
$sum: "$items.price" // Calculate sum of all item prices
},
itemCount: { $size: "$items" },
updatedAt: new Date()
}
}
]
)
// Update based on existing field values
db.users.updateMany(
{},
[
{
$set: {
ageGroup: {
$switch: {
branches: [
{ case: { $lt: ["$age", 18] }, then: "minor" },
{ case: { $lt: ["$age", 65] }, then: "adult" },
{ case: { $gte: ["$age", 65] }, then: "senior" }
],
default: "unknown"
}
}
}
}
]
)
// Check results
db.orders.find().pretty()
db.users.find({}, { name: 1, age: 1, ageGroup: 1 }).pretty()
Practical Update Examples
Real-world update scenarios and solutions
// Example 1: User profile update
function updateUserProfile(userId, profileData) {
var result = db.users.updateOne(
{ _id: userId },
{
$set: {
...profileData,
lastModified: new Date()
}
}
)
if (result.matchedCount === 0) {
print("User not found")
return false
}
print("Profile updated successfully")
return true
}
// Example 2: Inventory management
function updateInventory(productId, quantityChange) {
var result = db.products.updateOne(
{
_id: productId,
stock: { $gte: Math.abs(quantityChange) } // Ensure sufficient stock
},
{
$inc: { stock: quantityChange },
$set: { lastUpdated: new Date() }
}
)
if (result.matchedCount === 0) {
print("Product not found or insufficient stock")
return false
}
print("Inventory updated successfully")
return true
}
// Example 3: Bulk price update with conditions
function updatePricesByCategory(category, discountPercent) {
var result = db.products.updateMany(
{ category: category },
[
{
$set: {
originalPrice: "$price", // Store original price
price: {
$multiply: [
"$price",
{ $subtract: [1, discountPercent / 100] }
]
},
discountApplied: discountPercent,
saleStartDate: new Date()
}
}
]
)
print("Updated " + result.modifiedCount + " products in category: " + category)
return result.modifiedCount
}
// Usage examples
updateUserProfile(1, { email: "[email protected]", phone: "555-0123" })
updateInventory(101, -5) // Reduce stock by 5
updatePricesByCategory("electronics", 15) // 15% discount