Nodejs MongoDB delete document

MongoDB’s document is like a table’s row in RDBMS. to delete document from the collection through deleteOne() or deleteMany() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

delete one document through deleteOne() method

Firstly create the delete_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var where_condition={name:'Mathew'}
     dbo.collection("users").deleteOne(where_condition, function(err, res) {
      if (err) throw err;
       console.log("1 document deleted successfully");
       console.log("result:",res.result);
       console.log("deleted_count:",res.deletedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the delete_document.js file.


node delete_document.js
Output:-
1 document deleted successfully
result: { n: 1, ok: 1 }
deleted_count: 1

delete multiple documents through deleteMany() method

Firstly create the delete_documents.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
   if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var where_condition={name:/o/}
     dbo.collection("users").deleteMany(where_condition, function(err, res) {
      if (err) throw err;
       console.log("documents deleted successfully");
       //console.log(res);
       console.log("result:",res.result);
       console.log("deleted_count:",res.deletedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the delete_documents.js file.


node delete_documents.js
Output:-
documents deleted successfully
result: { n: 3, ok: 1 }
deleted_count: 3