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.
The following example updates the phone number of a user's document filter by its id.
UpdateOne
method returns an UpdateResult
result that indicates the result of the update operation.
MatchedCount: The number of documents matched your filter definition
ModifiedCount: The number of documents updated
IsAcknowledged: Indicates whether the result is acknowledged
UpsertedId: The upserted id, if one exists
Remember that if the document already has the same value that you want to update to, modifiedCount
will be 0
Update multiple documents
To update many documents at once, follow the same process but this time use the UpdateMany
method.
The following example filters user documents having salary greater than 1200 and less than 3500 and set the salary value to 4000.
Last updated