AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

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

(任意) 大文字と小文字の比較を含めるかどうかを指定します。

この引数が true の場合、ドライバーの動作は strength 引数の値によって異なります。

- strengthCollationStrength.Primary の場合、ドライバーは基本文字と大文字と小文字を比較します。
- strengthCollationStrength.Secondary の場合、ドライバーは基本文字、分音符号、その他の二次的な違い、および大文字と小文字を比較します。
- strength がその他の値の場合、この引数は無視されます。

この引数が false の場合、ドライバーは強度レベル Primary または Secondary での大文字と小文字の比較を含みません。

データ型: boolean
デフォルト: false

CaseLevel

caseFirst

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

Data Type: CollationCaseFirst
Default: CollationCaseFirst.Off

CaseFirst

strength

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

Data Type: CollationStrength
Default: CollationStrength.Tertiary

Strength

numericOrdering

(任意)ドライバーが数字の string を数値として比較するかどうかを指定します。この引数が

true102の場合、ドライバーは数字の10 210

falsestring10 2を数値として比較します。例は、"" という文字列を比較する場合、および1 "``2 `` の場合、ドライバーは値を および として処理し、 が大きいことを検出します。この引数が または除外されている場合、ドライバーは数字の string を string として比較します。例は、"" という文字列を比較する場合、および "q" の場合、ドライバーは一度に 1 文字を 1 文字ずつ比較します。のため "" はが10 "q" より小さい場合、ドライバーは "q" を見つけます。は、"" より小さくなければなりません。詳細については、2

MongoDB Serverマニュアルの「 照合制限

」を参照してください。データ型:boolean
デフォルト:false

NumericOrdering

alternate

(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)

Alternate

maxVariable

(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)

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

(任意) 発音区別符号を含む string を、string の後ろから前にソートするかどうかを指定します。

データ型: boolean
デフォルト: 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 ドキュメントを参照してください。