Operators

Set operator - $set

The $set operator is used to update the value of a specified field.

Builders<T<.Update.Set(doc => doc.<field>, <value>)

The sample updates the FirstName field of the first document in the collection.

Update/BasicOperators.cs
var collection = database
            .GetCollection<User>(Constants.UsersCollection);

// create an empty filter
var firstUserFilter = Builders<User>.Filter.Empty;

// create a Set operator update definition
var updateNameDefinition = Builders<User>.Update
            .Set(u => u.FirstName, "Chris");

// update the document
var updateNameResult = await collection
            .UpdateOneAsync(firstUserFilter, 
            updateNameDefinition);

Multiple fields update

You can update multiple document's fields in one operation by declaring more than one update definitions.

The sample updates the first document's Phone, Website and FavoriteSports (array field).

Inc operator - $inc

The $inc operator is used to increase the value of a specified field by a specified amount.

The sample increments the first document's salary.

Min operator - $min

The $min operator is used to update the value of a specified field only if the new value is less than the current value.

The sample decreases the first document's salary value from 3000 to 2000 πŸ’° .

Of course if the new value is equal to the current one, the update result will return that no documents updated.

Max operator - $max

The $max operator is used to update the value of a specified field only if the new value is greater than the current value.

The sample increases the first document's salary value from 3000 to 3500 πŸ’° .

Mul operator - $mul

The $mul operator is used to multiply the current value of a specified field by a specified value.

The sample doubles the first document's salary value from 1000 to 2000 using the $mul operator πŸ’° .

Unset operator - $unset

The $unset operator is used to remove a field from a document.

The sample removes ❌ the Website field from a user document.

​​ ⚑ Danger ​ βš‘β€‹β€‹ Danger ​ βš‘β€‹β€‹ Danger ​ ⚑

Rename operator - $rename

The $rename operator is used to rename a field.

The sample updates the Phone field of the first document to PhoneNumber using the $rename operator.

Last updated