Delete Documents (original) (raw)

In this section, we show you how to call the write operations to removedocuments from a collection in your MongoDB database.

If you want to remove existing documents from a collection, you can use deleteOne() to remove one document or deleteMany() for one or more documents. These methods accept a query document that matches the documents you want to delete.

Note

If your application uses information about the deleted document after deletion, you can use thecollection.findOneAndDelete()method, which has a similar interface to deleteOne() but also returns the deleted document.

You can specify the document or documents to be deleted by thedeleteOne() or deleteMany() write operations in a JSON object as follows:


const doc = {

  pageViews: {

    $gt: 10,

    $lt: 32768

  }

};

To delete the first matching document using the deleteOne() method or to delete all matching documents using the deleteMany() method, pass the document as the method parameter:


const deleteResult = await myColl.deleteOne(doc);

const deleteManyResult = await myColl.deleteMany(doc);

You can print the number of documents deleted by the operation by accessing the deletedCount field of the result for each of the method calls above as follows:


console.dir(deleteResult.deletedCount);

console.dir(deleteManyResult.deletedCount);

If the delete operation is successful, these statements print the number of documents deleted by the associated operation.

Note

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

Note

No TypeScript Specific Features

The following code example uses JavaScript. There are no TypeScript specific features of the driver relevant to this use case.

The following code is a complete, standalone file that performs a delete one operation:


1

// Delete a document

2

3

import { MongoClient } from "mongodb";

4

5

// Replace the uri string with your MongoDB deployment's connection string

6

const uri = "<connection string uri>";

7

8

const client = new MongoClient(uri);

9

10

async function run() {

11

  try {

12

    const database = client.db("sample_mflix");

13

    const movies = database.collection("movies");

14

15

    /* Delete the first document in the "movies" collection that matches

16

    the specified query document */

17

    const query = { title: "Annie Hall" };

18

    const result = await movies.deleteOne(query);

19

20

    /* Print a message that indicates whether the operation deleted a

21

    document */

22

    if (result.deletedCount === 1) {

23

      console.log("Successfully deleted one document.");

24

    } else {

25

      console.log("No documents matched the query. Deleted 0 documents.");

26

    }

27

  } finally {

28

    // Close the connection after the operation completes

29

    await client.close();

30

  }

31

}

32

// Run the program and print any thrown exceptions

33

run().catch(console.dir);

Running the preceding example results in the following output:


Successfully deleted one document.

If you run the example more than once, the code produces the following output because you deleted the matching document in the first run:


No documents matched the query. Deleted 0 documents.

Note

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

The following code is a complete, standalone file that performs a delete many operation:


1

// Delete multiple documents

2

3

import { MongoClient } from "mongodb";

4

5

// Replace the uri string with your MongoDB deployment's connection string.

6

const uri = "<connection string uri>";

7

8

const client = new MongoClient(uri);

9

10

async 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

28

run().catch(console.dir);


1

// Delete multiple documents

2

3

import { MongoClient } from "mongodb";

4

5

// Replace the uri string with your MongoDB deployment's connection string

6

const uri = "<connection string uri>";

7

8

const client = new MongoClient(uri);

9

10

async 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

27

run().catch(console.dir);

Running the preceding example for the first time results in the following output:

If you run the example more than once, you see the following output because you deleted the matching documents in the first run:

To learn more about any of the types or methods discussed in this guide, see the following API documentation: