Node.js MongoDB Delete

Node.js MongoDB Delete


Node.js MongoDB Delete is a process of removing a document or multiple documents from a MongoDB collection. In this tutorial, we will go through the steps of deleting a document from a MongoDB collection using Node.js.

Step 1: Connect to MongoDB

The first step is to connect to the MongoDB database. You can use the MongoClient module to connect to the database. Use the following code to connect to the database:

Make sure to replace the <username>, <password> and <dbname> with the appropriate values.

Step 2: Select the Collection

Once connected, you need to select the collection from which you want to delete the document. Use the following code to select the collection:

Make sure to replace "test" and "devices" with the appropriate values for your collection.

Step 3: Delete the Document

Finally, you can use the deleteOne() method to delete a single document from the collection. Use the following code to delete a document:


Make sure to replace the query object { name: "Device 1" } with the appropriate query to select the document you want to delete.

You can also use the deleteMany() method to delete multiple documents from the collection.

In this tutorial, we have covered the basic steps of deleting a document from a MongoDB collection using Node.js. You can use these steps as a starting point for your own projects and further explore the MongoDB API documentation to learn more about the different methods and options available for deleting data.