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.
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"
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) => {});
//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();
});
});
D:\nj-learn-mongo>node deleteMany-mongodb-nodejs.js
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
}