Update documents
Update one document
To update a document in MongoDB you need to configure 2 basic things:
A filter definition that defines which document should be updated
An update definition that defines what should be updated in the matched document
After configuring the above two, you use the UpdateOne
method on an IMongoCollection<T>
reference.
IMongoCollection<T>
.UpdateOne(FilterDefinition<T> filter,
UpdateDefinition<T> update)
The following example updates the phone number of a user's document filter by its id.
var personsCollection = usersDatabase.GetCollection<User>("users");
// Create an equality filter
var filter = Builders<User>.Filter
.Eq(person => person.Id, appPerson.Id);
// Create an update definition using the Set operator
var update = Builders<User>.Update
.Set(person => person.Phone, "123-456-789");
// Update the document
var personUpdateResult = await personsCollection.UpdateOneAsync(filter, update);
if (personUpdateResult.MatchedCount == 1 && personUpdateResult.ModifiedCount == 1)
{
Utils.Log( $"Document {appPerson.Id} Updated");
}
Update multiple documents
To update many documents at once, follow the same process but this time use the UpdateMany
method.
IMongoCollection<T>
.UpdateMany(FilterDefinition<T> filter,
UpdateDefinition<T> update)
The following example filters user documents having salary greater than 1200 and less than 3500 and set the salary value to 4000.
// Create a filter by combining a Greater & Less than filters
var salaryFilter = Builders<User>.Filter
.And(
Builders<User>.Filter.Gt(person => person.Salary, 1200),
Builders<User>.Filter.Lt(person => person.Salary, 3500)
);
// This is just for demonstration - validate the update result
var totalPersons = await personsCollection
.Find(salaryFilter).CountDocumentsAsync();
// Create an update definition using the Set operator
var updateDefinition = Builders<User>.Update
.Set(person => person.Salary, 4000);
var updateResult = await personsCollection
.UpdateManyAsync(salaryFilter, updateDefinition);
if (updateResult.MatchedCount.Equals(totalPersons))
{
Utils.Log($"Salary has been updated for {totalPersons}");
}
Last updated