Update Arrays
On this page
Overview
On this page, you can learn how to create UpdateDefinition
objects for array fields.
An UpdateDefinition
object specifies the kind of update operation to perform, the
fields to update, and the new value for each field, if applicable.
The .NET/C# Driver supports the array update operators and modifiers described in the
MongoDB Server manual.
To create an UpdateDefinition
object for one of these operators, call the corresponding
method from the Builders.Update
property.
The following sections describe these methods in more detail.
After you create an UpdateDefinition
object, pass it to the UpdateMany()
or UpdateManyAsync()
method. For more information about these methods, see
the Update Many page.
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; } [ ] 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; } [ ] public double[] Coordinates { get; set; } public string Street { get; set; } [ ] 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.
This collection is from the sample datasets provided by Atlas. See the Quick Start to learn how to create a free MongoDB cluster and load this sample data.
Add One Value
To add one value to the end of an array, call the Builders.Update.Push()
method.
This method accepts the following parameters:
Parameter | Description |
---|---|
| An expression that specifies the array field to add a value to. Data Type: |
| The value to add to the end of the array field. Data Type: |
The following code example uses the Push()
method to add a new GradeEntry
object
to the Grades
array in all matching documents:
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .Push(restaurant => restaurant.Grades, new GradeEntry() { Date = DateTime.Now, Grade = "A", Score = 96 }); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .Push(restaurant => restaurant.Grades, new GradeEntry() { Date = DateTime.Now, Grade = "A", Score = 96 }); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
Tip
Configure the Push Operation
To add a value at a specific position in an array, or to sort or slice the array after updating it, call the PushEach() method instead.
To add one value to the end of an array, but only if it doesn't already exist in the array,
call the Builders.Update.AddToSet()
method.
MongoDB Server determines whether the value already exists in the array by
comparing the value's BSON representation to the BSON representation of each
other element in the array.
The AddToSet()
method accepts the following parameters:
Parameter | Description |
---|---|
| An expression that specifies the array field to add a value to. Data Type: |
| The value to add to the end of the array field. Data Type: |
The following code example calls the AddToSet()
method to re-add the first
GradeEntry
object to the Grades
array in all matching documents. Because
the value already exists in the array, the update operation does nothing.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; var update = Builders<Restaurant>.Update .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; var update = Builders<Restaurant>.Update .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
Add Multiple Values
To add multiple values to an array, call the Builders.Update.PushEach()
method.
This method accepts the following parameters:
Parameter | Description |
---|---|
| An expression that specifies the array field to add one or more values to. Data Type: |
| The values to add to the array field. Data Type: |
| The number of elements to keep in the array, counted from the start of the array after updates. If the value is negative, the method keeps the specified number of elements from the end of the array. Data Type: |
| The position in the array at which to add the values. By default, the method adds the values to the end of the array. Data Type: |
| A Data Type: SortDefinition<TItem> |
The following code example uses the PushEach()
method to add two new GradeEntry
objects to the start of the Grades
array in all matching documents.
It then sorts the array elements in descending order by the values of their Score
fields.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} }; var scoreSort = Builders<GradeEntry>.Sort.Descending(g => g.Score); var update = Builders<Restaurant>.Update.PushEach( "Grades", newGrades, position: 0, sort: scoreSort); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} }; var scoreSort = Builders<GradeEntry>.Sort.Descending(g => g.Score); var update = Builders<Restaurant>.Update.PushEach( "Grades", newGrades, position: 0, sort: scoreSort); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
To add multiple values to an array, but only if they don't already exist in the array,
call the Builders.Update.AddToSetEach()
method.
This method accepts the following parameters:
Parameter | Description |
---|---|
| An expression that specifies the array field to add one or more values to. Data Type: |
| The values to add to the array field. Data Type: |
The following code example calls the AddToSetEach()
method to re-add the first
and second GradeEntry
objects to the Grades
array in all matching documents.
Because these values already exist in the array, the update operation does nothing.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); var firstGradeEntries = new List<GradeEntry> { doc.Grades[0], doc.Grades[1] }; var update = Builders<Restaurant>.Update .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); var firstGradeEntries = new List<GradeEntry> { doc.Grades[0], doc.Grades[1] }; var update = Builders<Restaurant>.Update .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
Remove Values
The following sections explain how to remove values from an array field.
First Value
To remove the first value from an array, call the Builders.Update.PopFirst()
method.
This method accepts the following parameter:
Parameter | Description |
---|---|
| An expression that specifies the array field to remove the first value from. Data Type: |
The following code example uses the PopFirst()
method to remove the first GradeEntry
object from the Grades
array in all matching documents:
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .PopFirst(restaurant => restaurant.Grades); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .PopFirst(restaurant => restaurant.Grades); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
Last Value
To remove the last value from an array, call the Builders.Update.PopLast()
method:
This method accepts the following parameter:
Parameter | Description |
---|---|
| An expression that specifies the array field to remove the last value from. Data Type: |
The following code example uses the PopLast()
method to remove the last GradeEntry
object from the Grades
array in all matching documents:
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .PopLast(restaurant => restaurant.Grades); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var update = Builders<Restaurant>.Update .PopLast(restaurant => restaurant.Grades); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
All Instances of a Value
To remove all instances of a specific value from an array, call the
Builders.Update.Pull()
method. This method accepts the following parameters:
Parameter | Description |
---|---|
| An expression that specifies the array field to remove the values from. Data Type: |
| The value to remove from the array field. Data Type: |
The following code example uses the Pull()
method to remove all instances of a
a specific GradeEntry
object from the Grades
array in all matching documents:
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateMany(filter, addUpdate); // Remove duplicates from Grades array var pullUpdate = Builders<Restaurant>.Update .Pull(restaurant => restaurant.Grades, newGrades[0]); var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); // Remove duplicates from Grades array var pullUpdate = Builders<Restaurant>.Update .Pull(restaurant => restaurant.Grades, newGrades[0]); var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); return result;
All Instances of Multiple Values
To remove all instances of more than one specific value from an array, call the
Builders.Update.PullAll()
method.
This method accepts the following parameters:
Parameter | Description |
---|---|
| An expression that specifies the array field to remove the values from. Data Type: |
| The values to remove from the array field. Data Type: |
The following code example uses the PullAll()
method to remove all instances of two
specific GradeEntry
objects from the Grades
array in all matching documents:
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateMany(filter, addUpdate); // Remove duplicates from Grades array var gradesToRemove = new List<GradeEntry> { newGrades[0], newGrades[2] }; var pullUpdate = Builders<Restaurant>.Update .PullAll(restaurant => restaurant.Grades, gradesToRemove); var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); // Remove duplicates from Grades array var gradesToRemove = new List<GradeEntry> { newGrades[0], newGrades[2] }; var pullUpdate = Builders<Restaurant>.Update .PullAll(restaurant => restaurant.Grades, gradesToRemove); var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); return result;
All Values That Match a Condition
To remove all values that match a specific condition from an array, call the
Builders.Update.PullFilter()
method.
This method accepts the following parameters:
Parameter | Description |
---|---|
| An expression that specifies the array field to remove the values from. Data Type: |
| A query filter that specifies the condition for values to remove. Data Type: FilterDefinition<TItem> |
The following code example uses the PullFilter()
method to remove all GradeEntry
objects where the Grade
value is "F"
from the Grades
array in the
matching documents:
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateMany(filter, addUpdate); // Remove all "Grade = F" values from Grades array var pullUpdate = Builders<Restaurant>.Update .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); return result;
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List<GradeEntry> { new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} }; var addUpdate = Builders<Restaurant>.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); // Remove all "Grade = F" values from Grades array var pullUpdate = Builders<Restaurant>.Update .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); return result;
Update Matching Values
To update a value in an array field, call the Builders.Update.Set()
method.
This method accepts the following parameters:
Parameter | Description |
---|---|
| An expression that specifies the array field to update. Data Type: |
| The new value to set into the array field. Data Type: |
You can use the
positional operator
with the Set()
method to query and update specific values in the array.
If you're using the LINQ3 provider, the .NET/C# Driver also supports LINQ syntax in
place of the positional operator.
The following sections describe different ways to update matching values in an array field.
First Matching Value
To update the first value in an array, you can use either the positional operator
($
) or LINQ syntax.
Select a Positional Operator or LINQ tab to
see the corresponding syntax.
The following example uses the Set()
method and the positional operator to
update the Grades
array in all matching documents. First,
it finds only the first GradeEntry
object in the Grades
array where the Grade
property has the value "A"
. Then, it updates the Score
property of the first matching
GradeEntry
object to 100.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli") & Builders<Restaurant>.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders<Restaurant>.Update .Set("grades.$.score", 100); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
Note
To use the positional operator, the array field must be part of the query filter.
The following example uses the Set()
method and the positional operator to
update the Grades
array in all matching documents. First,
it finds only the first GradeEntry
object in the Grades
array where the Grade
property has the value "A"
. Then, it updates the Score
property of the first matching
GradeEntry
object to 100.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli") & Builders<Restaurant>.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders<Restaurant>.Update .Set("grades.$.score", 100); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
Note
To use the positional operator, the array field must be part of the query filter.
The following example uses the Set()
and FirstMatchingElement()
methods to
update the Grades
array in all matching documents. First,
it finds only the first GradeEntry
object in the Grades
array where the
Grade
property has the value "A"
. Then, it updates the Score
property of
the first matching GradeEntry
object to 100.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli") & Builders<Restaurant>.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
The following example uses the Set()
and FirstMatchingElement()
methods to
update the Grades
array in all matching documents. First,
it finds only the first GradeEntry
object in the Grades
array where the
Grade
property has the value "A"
. Then, it updates the Score
property of
the first matching GradeEntry
object to 100.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli") & Builders<Restaurant>.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
All Matching Values
To update all values in an array that match a specified condition, you can use either
the filtered positional operator ($[<identifier>]
) or LINQ syntax.
Select a Positional Operator or LINQ tab to
see the corresponding syntax.
The following example uses the Set()
method and the filtered positional operator
to update the Score
property of all matching
GradeEntry
objects in the Grades
array to 100 in all matching documents.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List<ArrayFilterDefinition> { new BsonDocumentArrayFilterDefinition<Restaurant>( new BsonDocument { { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders<Restaurant>.Update .Set("grades.$[gradeEntry].grade", "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = _restaurantsCollection.UpdateMany(filter, update, updateOptions); return result;
The following example uses the Set()
method and the filtered positional operator
to update the Score
property of all matching
GradeEntry
objects in the Grades
array to 100 in all matching documents.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List<ArrayFilterDefinition> { new BsonDocumentArrayFilterDefinition<Restaurant>( new BsonDocument { { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders<Restaurant>.Update .Set("grades.$[gradeEntry].grade", "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = await _restaurantsCollection.UpdateManyAsync(filter, update, updateOptions); return result;
The following example uses the Set()
and AllMatchingElements()
methods
to update the Score
property of all matching
GradeEntry
objects in the Grades
array to 100 in all matching documents.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List<ArrayFilterDefinition> { new BsonDocumentArrayFilterDefinition<Restaurant>( new BsonDocument { { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Grade, "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = _restaurantsCollection.UpdateMany(filter, update, updateOptions); return result;
The following example uses the Set()
and AllMatchingElements()
methods
to update the Score
property of all matching
GradeEntry
objects in the Grades
array to 100 in all matching documents.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List<ArrayFilterDefinition> { new BsonDocumentArrayFilterDefinition<Restaurant>( new BsonDocument { { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Grade, "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = await _restaurantsCollection.UpdateManyAsync(filter, update, updateOptions); return result;
All Values
To update all values in an array that match a query filter, you can use either the
all-positional operator ($[]
) or LINQ syntax.
Select a Positional Operator or LINQ tab to
see the corresponding syntax.
The following example uses the Set()
method and the all-positional operator
to update the Score
property of all GradeEntry
objects in the Grades
array
to 100 in all matching documents.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders<Restaurant>.Update .Set("grades.$[].score", 100); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
The following example uses the Set()
method and the all-positional operator
to update the Score
property of all GradeEntry
objects in the Grades
array
to 100 in all matching documents.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders<Restaurant>.Update .Set("grades.$[].score", 100); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
The following example uses the Set()
and AllElements()
methods
to update the Score
property of all GradeEntry
objects in the Grades
array
to 100 in all matching documents.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.AllElements().Score, 100); var result = _restaurantsCollection.UpdateMany(filter, update); return result;
The following example uses the Set()
and AllElements()
methods
to update the Score
property of all GradeEntry
objects in the Grades
array
to 100 in all matching documents.
var filter = Builders<Restaurant>.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Grades.AllElements().Score, 100); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result;
API Documentation
For more information about any of the methods or types discussed in this guide, see the following API documentation: