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. 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.

The syntax for deleteOne is :                


Let's try it in our code block

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" };
	db.collection("details").deleteOne(query , (err , collection) => {
		if(err) throw err;
		console.log(collection.result.n + " Record(s) deleted successfully");


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
			ok: 1,
			n: 1
	connection: null,
	message: undefined,
	deletedCount: 1