fields

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: sync, async -->

Update Fields in Many Documents

Overview

On this page, you can learn how to use the MongoDB .NET/C# Driver to update fields in multiple MongoDB documents. This page describes how to create UpdateDefinition<TDocument> objects that specify the update operations you want to perform on fields. You can pass these objects to the update methods described on the [Update Many](https://www.mongodb.com/docs/drivers/csharp/current/crud/update-many.md#std-label-csharp-update-many page.

The .NET/C# Driver supports the field update operators described in the [MongoDB Server manual](https://www.mongodb.com/docs/manual/reference/operator/update/#fields. To specify an update operation, call the corresponding method from the Builders.Update property. The following sections describe these methods in more detail.

Note: Method Overloads

Many of the methods on this page have multiple overloads. The examples in this guide show only one definition of each method. For more information about the available overloads, see the API documentation.

Sample Data

The examples in this guide use the restaurants collection from the sample_restaurants database. The documents in this collection use the following Restaurant, Address, and GradeEntry classes as models:

public class Restaurant
{
    public ObjectId Id { get; set; }

    public string Name { get; set; }

    [BsonElement("restaurant_id")]
    public string RestaurantId { get; set; }

    public string Cuisine { get; set; }

    public Address Address { get; set; }

    public string Borough { get; set; }

    public List<GradeEntry> Grades { get; set; }
}
public class Address
{
    public string Building { get; set; }

    [BsonElement("coord")]
    public double[] Coordinates { get; set; }

    public string Street { get; set; }

    [BsonElement("zipcode")]
    public string ZipCode { get; set; }
}
public class GradeEntry
{
    public DateTime Date { get; set; }

    public string Grade { get; set; }

    public float? Score { get; set; }
}

Note:

The documents in the restaurants collection use the snake-case naming convention. The examples in this guide use a ConventionPack to deserialize the fields in the collection into Pascal case and map them to the properties in the Restaurant class.

To learn more about custom serialization, see [Custom Serialization.](https://www.mongodb.com/docs/drivers/csharp/current/serialization/poco.md#std-label-csharp-custom-serialization

This collection is from the sample datasets provided by Atlas. See the [Get Started with the .NET/C# Driver](https://www.mongodb.com/docs/drivers/csharp/current/get-started.md#std-label-csharp-get-started to learn how to create a free MongoDB cluster and load this sample data.

Increment a Value

To increment the value of a field by a specific amount, call the Builders.Update.Inc() method. This method accepts the following parameters:

Parameter Description
field An expression that specifies the field to increment. Data Type: Expression<Func<TDocument, TField>>
value The amount to increment the field by. Data Type: TField

The following code example uses the Inc() method to increment the Score value by 2 in the first GradeEntry object of the Grades array in all matching documents:

Synchronous

var filter = Builders<Restaurant>.Filter.Eq("name", "Shake Shack");

var update = Builders<Restaurant>.Update
    .Inc(restaurant => restaurant.Grades[0].Score, 2);

var result = _restaurantsCollection.UpdateMany(filter, update);

Multiply a Value

To multiply the value of a field by a specific amount, call the Builders.Update.Mul() method. This method accepts the following parameters:

Parameter Description
field An expression that specifies the field to update. Data Type: Expression<Func<TDocument, TField>>
value The amount to multiply the field by. Data Type: TField

The following code example uses the Mul() method to multiply the Score value by 1.25 in the first GradeEntry object of the Grades array in all matching documents:

Synchronous

var filter = Builders<Restaurant>.Filter.Eq("name", "Shake Shack");

var update = Builders<Restaurant>.Update
    .Mul(restaurant => restaurant.Grades[0].Score, 1.25f);

var result = _restaurantsCollection.UpdateMany(filter, update);

Rename a Field

To rename a field, call the Builders.Update.Rename() method. This method accepts the following parameters:

Parameter Description
field An expression that specifies the field to rename. Data Type: Expression<Func<TDocument, TField>>
newName The new name for the field. Data Type: string

The following code example uses the Rename() method to rename the Address field to location in all matching documents:

Synchronous

var filter = Builders<Restaurant>.Filter.Eq("name", "Shake Shack");

var update = Builders<Restaurant>.Update
    .Rename(restaurant => restaurant.Address, "location");

var result = _restaurantsCollection.UpdateMany(filter, update);

Note:

The preceding code examples use the field name location because this matches the naming scheme of the field names in MongoDB, not the property names in the Restaurant class.

Set a Value

To set the value of a field to a specific value, call the Builders.Update.Set() method. This method accepts the following parameters:

Parameter Description
field An expression that specifies the field to update. Data Type: Expression<Func<TDocument, TField>>
value The value to set the field to. Data Type: TField

The following code example uses the Set() method to rename the recommended field to true in all matching documents:

Synchronous

var filter = Builders<Restaurant>.Filter.Eq("name", "Shake Shack");

var update = Builders<Restaurant>.Update
    .Set("recommended", true);

var result = _restaurantsCollection.UpdateMany(filter, update);

Note:

The preceding code examples use the field name recommended because this matches the naming scheme of the field names in MongoDB, not the property names in the Restaurant class.

Set by Comparison

To update the value of the field to a specified value, but only if the specified value is greater than the current value of the field, call the Builders.Update.Max() method. This method accepts the following parameters:

Parameter Description
field An expression that specifies the field to update. Data Type: Expression<Func<TDocument, TField>>
value The value to set the field to. Data Type: TField

To update the value of the field to a specified value, but only if the specified value is less than the current value of the field, call the Builders.Update.Min() method. This method accepts the following parameters:

Parameter Description
field An expression that specifies the field to update. Data Type: Expression<Func<TDocument, TField>>
value The value to set the field to. Data Type: TField

The following code example uses the Max() method to set the Score field of the first GradeEntry object to the greater of 20 and the current value in all matching documents:

Synchronous

var filter = Builders<Restaurant>.Filter.Eq("name", "Shake Shack");

var update = Builders<Restaurant>.Update
    .Max(restaurant => restaurant.Grades[0].Score, 20);

var result = _restaurantsCollection.UpdateMany(filter, update);

Set on Insert

To set the value of a field only if the document was upserted by the same operation, call the Builders.Update.SetOnInsert() method. This method accepts the following parameters:

Parameter Description
field An expression that specifies the field to update. Data Type: Expression<Func<TDocument, TField>>
value The value to set the field to. Data Type: TField

The following code example uses the SetOnInsert() method to set the recommended field to true in all matching documents:

Synchronous

var filter = Builders<Restaurant>.Filter.Eq("name", "Patty's Pies");

var update = Builders<Restaurant>.Update
    .SetOnInsert("recommended", true);

var result = _restaurantsCollection.UpdateMany(
  filter, update, new UpdateOptions { IsUpsert = true }
);

Note:

The preceding code examples use the field name recommended because this matches the naming scheme of the field names in MongoDB, not the property names in the Restaurant class.

To learn more about upserting documents, see [Configuration Options](https://www.mongodb.com/docs/drivers/csharp/current/crud/update-many.md#std-label-csharp-update-many-options-1 in the Update Many guide.

Set the Current Date

To set the value of a field to the current date and time, call the Builders.Update.CurrentDate() method. This method accepts the following parameters:

Parameter Description
field An expression that specifies the field to update. Data Type: Expression<Func<TDocument, TField>>
type The format of the date and time, defined in the UpdateDefinitionCurrentDateType enum. The default value is null. Data Type: UpdateDefinitionCurrentDateType?

The following code example uses the CurrentDate() method to update the Date field of the first GradeEntry object to the current date in all matching documents:

Synchronous

var filter = Builders<Restaurant>.Filter.Eq("name", "Shake Shack");

var update = Builders<Restaurant>.Update
    .CurrentDate(restaurant => restaurant.Grades[0].Date);

var result = _restaurantsCollection.UpdateMany(filter, update);

Unset a Field

To remove a field from a document, call the Builders.Update.Unset() method. This method accepts the following parameter:

Parameter Description
field An expression that specifies the field to remove. Data Type: Expression<Func<TDocument, TField>>

The following code example uses the Unset() method to remove the Cuisine field in all matching documents:

Synchronous

var filter = Builders<Restaurant>.Filter.Eq("name", "Shake Shack");

var update = Builders<Restaurant>.Update
    .Unset(restaurant => restaurant.Cuisine);

var result = _restaurantsCollection.UpdateMany(filter, update);

API Documentation

For more information about any of the methods discussed in this guide, see the following API documentation: