Dark Mode
Image

Node.js MongoDB Remove

In MongoDB, you can delete records or documents by using the remove() method. The first parameter of the remove() method is a query object which specifies the document to delete.

Example

Remove the record of employee whose address is Ghaziabad.

Create a js file named "remove.js", having the following code:

  1. var http = require('http');  
  2. var MongoClient = require('mongodb').MongoClient;  
  3. var url = "mongodb://localhost:27017/ MongoDatabase";  
  4. MongoClient.connect(url, function(err, db) {  
  5. if (err) throw err;  
  6. var myquery = { address: 'Ghaziabad' };  
  7. db.collection("employees").remove(myquery, function(err, obj) {  
  8. if (err) throw err;  
  9. console.log(obj.result.n + " record(s) deleted");  
  10. db.close();  
  11. });  
  12. });  

Open the command terminal and run the following command:

  1. Node remove.js  

Node.js Remove 1

Verification

You can check that the record having address "Ghaziabad" is deleted and only following records are available now:

Node.js Remove 2

Comment / Reply From