In this part of the mongodb operations using node.js tutorial series , we will learn about deleting all
the occurrences of data matching a certain criteria from a mongodb collection
using node.js
.
We will start by including mongodb
npm package as shown below :
var mongo = require('mongodb');
Establish a connection between the mongoDb database and our node.js app using the following :
var new_db = "mongodb://localhost:27017/demo_db"
deleteMany()
is an inbuilt method of mongodb
which is used to delete all the
occurrences of data obtained using the search query.
The syntax of deleteMany()
function is given below :
db.collection("NAME_OF_THE_COLLECTION").deleteMany(SEARCH_CONDITION ,(CALLBACK_FUNCTION) => {});
//delete-many.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();
});
});
>node delete-many.js
2 Record(s) deleted successfully
{
result:
{
ok: 1,
n: 2
},
connection: null,
message: undefined,
deletedCount: 2
}
In this article we learned about
monogdb
npm package in your app. deleteMany()
operation in mongodb using node.js