MongoDB provides several methods to update existing documents in a collection:
updateOne()
: Updates a single document that matches the filter.
Example:
db.users.updateOne(
{ name: 'John Doe' },
{ $set: { age: 31, status: 'active' } }
)
updateMany()
: Updates all documents that match the filter.
Example:
db.users.updateMany(
{ status: 'inactive' },
{ $set: { status: 'active' } }
)
replaceOne()
: Replaces a single document that matches the filter with a new document.
Example:
db.users.replaceOne(
{ name: 'John Doe' },
{ name: 'John Doe', age: 31, email: 'john.new@example.com' }
)
Update operators:
$set
: Sets the value of a field.$unset
: Removes the specified field.$inc
: Increments the value of a field by a specified amount.$push
: Adds an element to an array field.$pull
: Removes all instances of a value from an array.Example using multiple operators:
db.users.updateOne(
{ name: 'John Doe' },
{
$set: { status: 'active' },
$inc: { age: 1 },
$push: { interests: 'hiking' }
}
)
Upsert: If set to true, creates a new document when no document matches the filter. Example:
db.users.updateOne(
{ email: 'newuser@example.com' },
{ $set: { name: 'New User', age: 25 } },
{ upsert: true }
)
ArrayFilters: Allows updating specific array elements that match certain conditions. Example:
db.users.updateMany(
{ 'scores.subject': 'math' },
{ $set: { 'scores.$[element].score': 95 } },
{ arrayFilters: [{ 'element.score': { $lt: 90 } }] }
)