In this tutorial, we are going to delete documents (records) from a collection (table) in MongoDB via Node.Js. There are two ways to delete documentation deleting document one by one and delete all the matched records in one go.
Topics Covered
- Delete One – Delete single document from matched documents in a Collection
- Delete Many – Delete all matched documents from Collection
Delete One – Delete single document from matched documents in a Collection
We have lot of documents in a collection, we will match the documents and delete the single document out of the multiple documents that we match using deleteOne().
findone.js
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/college";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var myquery = { name: 'Rohit' };
db.collection("students").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
db.close();
});
});
Delete Many – Delete all matched documents from Collection
We will match document in the collection and delete all the documents that match using deletemany().
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/college";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var myquery = { name: /^O/ };
db.collection("students").deleteMany(myquery, function(err, obj) {
if (err) throw err;
console.log(obj.result.n + " document(s) deleted");
db.close();
});
});
Learn More-