Overview
このガイドでは、削除操作を使用して MongoDB コレクションからドキュメントを削除する方法を学習できます。
サンプル データ
このガイドの例では、 sample_restaurants
データベースの restaurants
コレクションを使用します。 このコレクションのドキュメントでは、次のRestaurant
、 Address
、 GradeEntry
クラスをモデルとして使用します。
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; } }
注意
restaurants
コレクションのドキュメントは、スニペット ケースの命名規則を使用します。このガイドの例では、ConventionPack
を使用してコレクション内のフィールドをパスカル ケースに逆シリアル化し、Restaurant
クラスのプロパティにマップします。
カスタム直列化について詳しくは、「 カスタム直列化 」を参照してください。
このコレクションは、Atlas が提供する サンプルデータセット からのものです。無料のMongoDBクラスターを作成し、このサンプルデータをロードする方法については、 「 .NET/ C#ドライバーを使い始める 」を参照してください。
削除操作
削除操作 を使用して、クエリフィルターに一致するドキュメントを削除します。 クエリフィルターは、 クエリフィルター ドキュメントの条件に基づいて、どのレコードが削除対象として選択されるかを決定します。 MongoDB では、次の方法で削除操作を実行できます。
DeleteOne()
は、クエリフィルターに一致する最初のドキュメントを削除します。DeleteMany()
は、クエリフィルターに一致するすべてのドキュメントを削除します
単一ドキュメントの削除
次のコードは、同期 DeleteOne()
メソッドまたは非同期 DeleteOneAsync()
メソッドを使用して 1 つのドキュメントを削除する方法を示しています。
var result = _restaurantsCollection.DeleteOne(filter);
var result = await _restaurantsCollection.DeleteOneAsync(filter);
複数のドキュメントの削除
次のコードは、同期 DeleteMany()
メソッドまたは非同期 DeleteManyAsync()
メソッドを使用して、一致したドキュメントをすべて削除する方法を示しています。
var result = _restaurantsCollection.DeleteMany(filter);
var result = await _restaurantsCollection.DeleteManyAsync(filter);
Tip
これらのメソッドを使用して実行可能な例については、追加情報を参照してください。
パラメーター
DeleteOne()
メソッドとDeleteMany()
メソッドでは、一致するドキュメントを指定するクエリフィルターを渡す必要があります。 クエリフィルターの作成方法について詳しくは、「 ドキュメントのクエリ 」のチュートリアルを参照してください。
Both methods optionally take a DeleteOptions
type as an additional parameter, which represents options you can use to configure the delete operation. DeleteOptions
プロパティを指定しない場合、ドライバーは削除操作をカスタマイズしません。
DeleteOptions
タイプでは、次のプロパティを持つオプションを構成できます。
プロパティ | 説明 |
---|---|
| Gets or sets the type of language collation to use when sorting
results. See the Collation section of this page for more
information. |
| Gets or sets the comment for the operation. See the delete command
fields
for more information. |
| Gets or sets the index to use to scan for documents. See the delete
statements
for more information. |
| Gets or sets the let document. See the delete command
fields
for more information. |
照合
操作の 照合 を構成するには、 照合 クラスのインスタンスを作成します。
次の表では、Collation
コンストラクターが受け入れるパラメーターを説明しています。また、各設定の値を読み取るために使用できる対応するクラスプロパティも一覧表示されます。
Parameter | 説明 | クラスプロパティ |
---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of
supported locales,
see Collation Locales and Default Parameters
in the MongoDB Server Manual. If you want to use simple binary comparison, use the Collation.Simple static
property to return a Collation object with the locale set to "simple" .Data Type: string |
|
| (Optional) Specifies whether to include case comparison. When this argument is true , the driver's behavior depends on the value of
the strength argument:- If strength is CollationStrength.Primary , the driver compares base
characters and case.- If strength is CollationStrength.Secondary , the driver compares base
characters, diacritics, other secondary differences, and case.- If strength is any other value, this argument is ignored.When this argument is false , the driver doesn't include case comparison at
strength level Primary or Secondary .Data Type: boolean Default: false |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. Data Type: CollationCaseFirst Default: CollationCaseFirst.Off |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: CollationStrength Default: CollationStrength.Tertiary |
|
| (Optional) Specifies whether the driver compares numeric strings as numbers. If this argument is true , the driver compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the driver treats the values
as 10 and 2, and finds 10 to be greater.If this argument is false or excluded, the driver compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the driver
compares one character at a time. Because "1" is less than "2", the driver finds
"10" to be less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: boolean Default: false |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base
characters for purposes of comparison. Data Type: CollationAlternate Default: CollationAlternate.NonIgnorable (spaces and punctuation are
considered base characters) |
|
| (Optional) Specifies which characters the driver considers ignorable when
the alternate argument is CollationAlternate.Shifted .Data Type: CollationMaxVariable Default: CollationMaxVariable.Punctuation (the driver ignores punctuation
and spaces) |
|
| (Optional) Specifies whether the driver normalizes text as needed. Most text doesn't require normalization. For more information about
normalization, see the ICU documentation. Data Type: boolean Default: false |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: boolean Default: false |
|
照合の詳細については、 MongoDB Serverマニュアルの 照合 ページを参照してください。
例
次のコードでは、 DeleteMany()
メソッドを使用して「bool_ 1 」インデックスを検索し、 address.street
フィールド値に "Pearl Center" というフレーズが含まれるすべてのドキュメントを削除します。
var filter = Builders<Restaurant>.Filter .Regex("address.street", "Pearl Street"); DeleteOptions opts = new DeleteOptions { Hint = "borough_1" }; Console.WriteLine("Deleting documents..."); var result = _restaurantsCollection.DeleteMany(filter, opts); Console.WriteLine($"Deleted documents: {result.DeletedCount}"); Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}");
Deleting documents... Deleted documents: 26 Result acknowledged? True
Tip
上記の例でDeleteMany()
ではなくDeleteOne()
メソッドが使用されている場合、ドライバーは26に一致したドキュメントの最初の を削除します。
戻り値
DeleteOne()
メソッドとDeleteMany()
メソッドはDeleteResult
型を返します。 このタイプには、削除されたドキュメント数を示すDeletedCount
プロパティと、結果が確認されたかどうかを示すIsAcknowledged
プロパティが含まれています。 クエリフィルターがどのドキュメントにも一致しない場合、ドキュメントは削除されず、 DeletedCount
は0です。
詳細情報
削除操作の実行可能な例については、次の使用例を参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。