delete all the occurances of specific data from a Mongodb database using Node.js


What do we intend to make ?

In this Chapter , we will learn about deleting the first occurance of the data searched using a search query parameter in the deleteOne method of mongoDb database.

Let's Start !

Step - 1 : Including Packages
We will start by requiring the package. We are using the following package in our application :

		        

var mongo = require('mongodb');
                
	            


Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.

		        

var new_db = "mongodb://localhost:27017/demo_db"



                
	            

  • demo_db is the name of the database. You can change it as per your wish.
  • 27017 is the port where our mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

Step - 3 : delete all occurances
deleteMany() is the inbuilt method of mongodb which is used to delete all the occurances of the data provided in the search query.

Syntax
The syntax for deleteMany is :                

		        
db.collection("NAME_OF_THE_COLLECTION").deleteMany(SEARCH_CONDITION ,(CALLBACK_FUNCTION) => {});
				
	            

Let's try it in our code block

		        
//deleteMany-mongodb-nodejs.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//connecting to the db
mongo.connect(new_db ,(error , db) => {
	if (error){
		throw error;
	}
	
	//Search query for deletion
	var query = { age : "above 22" };
	
	//Accessing the collection
	db.collection("details").deleteMany(query , (err , collection) => {
		if(err) throw err;
		console.log(collection.result.n + " Record(s) deleted successfully");
		console.log(collection);
		db.close();
	});
});




                
	            

You can run the above code using the following command :

		        

D:\nj-learn-mongo>node deleteMany-mongodb-nodejs.js

				
	            

The output of the above code is :

		        

D:\nj-learn-mongo>node deleteMany-mongodb-nodejs.js
2 Record(s) deleted successfully
{ 
	result: 
		{ 
			ok: 1,
			n: 2
		},
	connection: null,
	message: undefined,
	deletedCount: 2 
}