delete the first occurance 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
deleteOne() is the inbuilt method of mongodb which is used to delete the first occurance of the data provided in the search query.

Syntax
The syntax for deleteOne is :                

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

Let's try it in our code block

		        
//deleteOne-mongodb-nodejs.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//connecting to the database using nodejs
mongo.connect(new_db ,(error , db) => {
	if (error){
		throw error;
	}
	//query stores the search condition	
	var query = { age : "above 22" };
	
	//Accessing a COLLECTION IN MONGODB USING NODE.JS
	db.collection("details").deleteOne(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 deleteOne-mongodb-nodejs.js

				
	            

The output of the above code is :

		        

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