πŸ“Update

Overview

MongoDB provides a set of update operators to help you update values on your collections' documents. This section contains several samples showing how to use these operators to update:

  • Top level fields

  • Embedded fields

  • Array fields

Complex update operations such as updating embedded fields, adding or removing items in embedded array fields might be straight forward when building the queries in the Shell but not so much when using the MongoDB C# driver

The section contains samples for the following operators:

Other than the update operations there are also samples showing how to replace documents and array fields.

To create update operations using the MongoDB C# driver you need to create one or more update definitions. The syntax to create an update definition is the following:

Syntax: Builders<T>.Update.<Operator>(<field>,<value>)

Here's' an example:

var multiUpdateDefinition = Builders<User>.Update
    .Set(u => u.Phone, "123-456-789") // update 1
    .Inc(u => u.Salary, 300) // update 2
    .Set(u => u.FavoriteSports, 
        new List<string> 
        { "Soccer", "Basketball" }); // update 3

UpdateOne & UpdateMany

To update one or more documents use the UpdateOne and UpdateMany IMongoCollection<T> respectively.

Syntax: IMongoCollection<T>.UpdateOne(<filter>,<update-definition>)

Syntax: IMongoCollection<T>.UpdateMany(<filter>,<update-definition>)

{
	"acknowledged" : true,
	"matchedCount" : 1,
	"modifiedCount" : 1
}

Last updated