Docs Menu
Docs Home
/ / /
C#/.NET
/ / / /

配列の更新

項目一覧

  • Overview
  • サンプル データ
  • 1 つの値を追加
  • 複数の値の追加
  • Remove Values
  • 最初の値
  • 最後の値
  • 値のすべてのインスタンス
  • 複数の値のすべてのインスタンス
  • 条件に一致するすべての値
  • 一致する値の更新
  • 最初に一致する値
  • すべて一致する値
  • All Values
  • API ドキュメント

このページでは、配列フィールド用のUpdateDefinition {0 オブジェクトを作成する方法を学びます。 AnUpdateDefinition オブジェクト specifies the kind of update 操作 to perform, the fields to update, and the new value for each フィールド, if applicable.

The .NET/ C# Driver supports the array update operators and modifiers described in the MongoDB Server manual . To create anUpdateDefinition オブジェクト for one of these operators, call the corresponding method from theBuilders.Update プロパティ.次のセクションでは、これらの方法について詳しく説明します。

After you create anUpdateDefinition オブジェクト, pass it to theUpdateMany() orUpdateManyAsync() method.これらのメソッドの詳細については、 UpdateMany ページを参照してください。

注意

メソッドのオーバーロード

このページのメソッドの多くには、複数のオーバーロードがあります。 The examples in this ガイド show only one definition of each method. For more information about the available overloads, see the API documentation.

このガイドの例では、 sample_restaurantsデータベースのrestaurantsコレクションを使用します。 このコレクションのドキュメントでは、次のRestaurantAddressGradeEntryクラスをモデルとして使用します。

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; }
}

注意

restaurantsコレクションのドキュメントは、スニペット ケースの命名規則を使用します。このガイドの例では、ConventionPack を使用してコレクション内のフィールドをパスカル ケースに逆シリアル化し、Restaurantクラスのプロパティにマップします。

カスタム直列化について詳しくは、「カスタム直列化」を参照してください。

このコレクションは、Atlas が提供するサンプル データセットから構成されています。 MongoDB クラスターを無料で作成して、このサンプル データをロードする方法については、クイック スタートを参照してください。

配列の末尾に 1 つの値を追加するには、Builders.Update.Push() メソッドを呼び出します。このメソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

value

データ型: TItem

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

プッシュ操作の設定

配列内の特定の位置に値を追加したり、配列を更新した後に配列をソートしたりスライスしたりするには、代わりに RustEach() メソッドを呼び出します。

配列の末尾に 1 つの値を追加するには、配列内にまだ存在しない場合のみ、 Builders.Update.AddToSet()メソッドを呼び出します。 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.

AddToSet() メソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

value

データ型: TItem

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;

配列に複数の値を追加するには、Builders.Update.PushEach() メソッドを呼び出します。このメソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

values

データ型: IEnumerable<TItem>

slice

更新後に配列の先頭からカウントした、配列に保持する要素の数。値が負の場合、メソッドは配列の末尾から指定された数の要素を保持します。

データ型: int?

position

配列内で値を追加する位置。 By デフォルト, the method adds the values to the end of the array.

データ型: int?

sort

データ型: SortDefinition<TItem>

The following code 例 uses the PushEach() method to add two new GradeEntry objects to the start of the Grades array in all matching documents.次に、配列要素を Score フィールドの値で降順にソートします。

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;

配列に複数の値を追加するには、それらが配列にまだ存在しない場合にのみ、 Builders.Update.AddToSetEach()メソッドを呼び出します。このメソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

values

データ型: IEnumerable<TItem>

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;

配列から最初の値を削除するには、Builders.Update.PopFirst() メソッドを呼び出します。このメソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

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;

配列から最後の値を削除するには、Builders.Update.PopLast() メソッドを呼び出します。このメソッドは次のパラメータを受け入れます。

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

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;

配列から特定の値のすべてのインスタンスを削除するには、Builders.Update.Pull() メソッドを呼び出します。このメソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

value

データ型: TItem

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;

配列から複数の特定の値のすべてのインスタンスを削除するには、Builders.Update.PullAll() メソッドを呼び出します。このメソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

values

データ型: IEnumerable<TItem>

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;

配列から特定の条件に一致するすべての値を削除するには、Builders.Update.PullFilter() メソッドを呼び出します。このメソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

filter

データ型: FilterDefinition<TItem>

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;

To update a value in an array フィールド, call the Builders.Update.Set() method.このメソッドは次のパラメーターを受け入れます:

Parameter
説明

field

データ型: Expression<Func<TDocument, IEnumerable<TItem>>>

value

データ型: TItem

位置演算子Set() メソッドと併用して、配列内の特定の値をクエリしてアップデートできます。 If you're using the LINQ3 provider, the .NET/ C# Driver also supports LINQ 構文 in place of the positional operator.

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;

注意

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;

注意

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;

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;

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;

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;

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;

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;

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;

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;

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;

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 ドキュメントを参照してください。

戻る

フィールド