Docs Menu
Docs Home
/ / /
Node.js ドライバー
/ /

複数のドキュメントの削除

collection.deleteMany() メソッドを使用して、コレクション内の複数のドキュメントを一度に削除できます使用して複数のドキュメントを挿入できます。 クエリ ドキュメントを deleteMany()メソッドに渡して、削除するコレクション内のドキュメントのサブセットを指定します。 クエリ ドキュメントを指定しない場合(または空のドキュメントを指定した場合)、MongoDB はコレクション内のすべてのドキュメントを照合し、それらを削除します。 deleteMany()を使用してコレクション内のすべてのドキュメントを削除できますが、 drop() の使用を検討してください 代わりに使用することで、パフォーマンスが向上し、コードがクリアされます。

deleteMany() メソッドの 2 番目のパラメーターで渡される options オブジェクトで、さらにオプションを指定できます。詳細については、「deleteMany() API ドキュメント」を参照してください。

次のスニペットは、movies コレクションから複数のドキュメントを削除します。これは、"Santa Claus" というタイトルの映画を見つけて削除するようにクエリを構成するクエリ ドキュメントを使用します。

注意

この例を使用して、MongoDB のインスタンスに接続し、サンプルデータを含むデータベースと交流できます。MongoDB インスタンスへの接続とサンプルデータセットの読み込みの詳細については、 使用例ガイドを参照してください。

1// Delete multiple documents
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string.
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 /* Delete all documents that match the specified regular
16 expression in the title field from the "movies" collection */
17 const query = { title: { $regex: "Santa" } };
18 const result = await movies.deleteMany(query);
19
20 // Print the number of deleted documents
21 console.log("Deleted " + result.deletedCount + " documents");
22 } finally {
23 // Close the connection after the operation completes
24 await client.close();
25 }
26}
27// Run the program and print any thrown exceptions
28run().catch(console.dir);
1// Delete multiple documents
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 /* Delete all documents that match the specified regular
16 expression in the title field from the "movies" collection */
17 const result = await movies.deleteMany({ title: { $regex: "Santa" } });
18
19 // Print the number of deleted documents
20 console.log("Deleted " + result.deletedCount + " documents");
21 } finally {
22 // Close the connection after the operation completes
23 await client.close();
24 }
25}
26// Run the program and print any thrown exceptions
27run().catch(console.dir);

上記の例を初めて実行すると、次の出力が表示されます。

Deleted 19 documents

この例えを複数回実行すると、最初の実行で一致したドキュメントが削除されるため、次の出力が表示されます。

Deleted 0 documents

戻る

ドキュメントの削除