Docs Menu
Docs Home
/ / /
Node.js
/ /

Delete Multiple Documents

You can delete multiple documents in a collection at once using the collection.deleteMany() method. Pass a query document to the deleteMany() method to specify a subset of documents in the collection to delete. If you do not provide a query document (or if you provide an empty document), MongoDB matches all documents in the collection and deletes them. While you can use deleteMany() to delete all documents in a collection, consider using drop() instead for better performance and clearer code.

You can specify additional options in the options object passed in the second parameter of the deleteMany() method. For more detailed information, see the deleteMany() API documentation.

The following snippet deletes multiple documents from the movies collection. It uses a query document that configures the query to match and delete movies with the title "Santa Claus".

Note

You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const movies = database.collection("movies");
12 // Query for all movies with a title containing the string "Santa"
13 const query = { title: { $regex: "Santa" } };
14
15 const result = await movies.deleteMany(query);
16 console.log("Deleted " + result.deletedCount + " documents");
17 } finally {
18 await client.close();
19 }
20}
21run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 title: string;
10}
11
12async function run() {
13 try {
14 const database = client.db("sample_mflix");
15 const movies = database.collection<Movie>("movies");
16 const result = await movies.deleteMany({ title: { $regex: "Santa" } });
17 console.log("Deleted " + result.deletedCount + " documents");
18 } finally {
19 await client.close();
20 }
21}
22run().catch(console.dir);

The first time you run the preceding example, you should see the following output:

Deleted 19 documents

On subsequent runs of the example, as you already deleted all relevant documents, you should see the following output:

Deleted 0 documents

Back

Delete a Document