Node & MongoDB – Delete Document


Node & MongoDB – Delete Documents



”;


To delete documents of a collection, you can use collection.deleteOne() or collection.deleteMany() methods to delete one or multiple documents.


database.collection("sampleCollection").deleteOne(query, function(error, result) {
   if (error) throw error;
   console.log(''Document deleted.'');
});
database.collection("sampleCollection").deleteMany(query, function(error, result) {
   if (error) throw error;
   console.log(result.result.n + " document(s) deleted.");
});

Example

Try the following example to delete a document in a mongodb collection −

Copy and paste the following example as mongodb_example.js −


const MongoClient = require(''mongodb'').MongoClient;
// Prepare URL
const url = "mongodb://localhost:27017/";
// make a connection to the database
MongoClient.connect(url, function(error, client) {
   if (error) throw error;
   console.log("Connected!");
   // Connect to the database
   const database = client.db(''myDb'');   database.collection("sampleCollection").deleteOne({First_Name:''Mahesh''}, function(error, result) {
      if (error) throw error;
      console.log(''Document Deleted.'');
   });   
   // close the connection
   client.close();
});

Output

Execute the mysql_example.js script using node and verify the output.


node mongodb_example.js
Connected!
Document Deleted.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *