Docs Menu
Docs Home
/ / /
C#/.NET ドライバー
/

Delete Documents

このガイドでは、削除操作を使用して MongoDB コレクションからドキュメントを削除する方法を学習できます。

このガイドの例では、 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クラスターを作成し、このサンプルデータをロードする方法については、 「 .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タイプでは、次のプロパティを持つオプションを構成できます。

プロパティ
説明

Collation

Gets or sets the type of language collation to use when sorting results. See the Collation section of this page for more information.

Comment

Gets or sets the comment for the operation. See the delete command fields for more information.

Hint

Gets or sets the index to use to scan for documents. See the delete statements for more information.

Let

Gets or sets the let document. See the delete command fields for more information.

操作の 照合 を構成するには、 照合 クラスのインスタンスを作成します。

次の表では、Collation コンストラクターが受け入れるパラメーターを説明しています。また、各設定の値を読み取るために使用できる対応するクラスプロパティも一覧表示されます。

Parameter
説明
クラスプロパティ

locale

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

Locale

caseLevel

(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

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Default: CollationStrength.Tertiary

Strength

numericOrdering

(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

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(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

Normalization

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: boolean
Default: false

Backwards

照合の詳細については、 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 ドキュメントを参照してください。

戻る

ドキュメントの置換

項目一覧