Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb difference remove() vs findOneAndDelete() vs deleteOne()

In express and mongodb I want delete document by id findOneAndDelete() Can not delete by _id, can only delete by field ! why ?

db.collection('quotes').findOneAndDelete({name: req.body.name}, (err, result) => {     if (err) return res.send(500, err)   })  var ObjectId = require('mongodb').ObjectId;   var collection = db.collection('quotes');   collection.remove({_id: new ObjectId(req.body.id)}, function(err, result) {       if (err) {           console.log(err);       } else {           res.send('A darth vadar quote got deleted')       }   });    var mongodb = require('mongodb');   db.collection('quotes', function(err, collection) {     collection.deleteOne({_id: new mongodb.ObjectID(req.body.id)});   }); 

Difference of three functions?

like image 220
Nguyen Don Tinh Avatar asked Mar 10 '17 10:03

Nguyen Don Tinh


People also ask

What is the difference between remove and deleteOne in MongoDB?

deleteOne() is used to delete a single document. remove() is a deprecated function and has been replaced by deleteOne() (to delete a single document) and deleteMany() (to delete multiple documents)

What is the difference between findOneAndRemove and findOneAndDelete?

Both of them are almost similar except findOneAndRemove uses findAndModify with remove flag and time complexity will be a bit higher compare to findOneAndDelete because you are doing an update. Delete are always faster. Both functions send the exact same command over the wire to MongoDB.

What does findOneAndDelete return?

Returns the deleted document.

How do you use findOneAndDelete?

Mongoose | findOneAndDelete() Function The findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.


1 Answers

In short:

  • findOneAndDelete() returns the deleted document after having deleted it (in case you need its contents after the delete operation);
  • deleteOne() is used to delete a single document
  • remove() is a deprecated function and has been replaced by deleteOne() (to delete a single document) and deleteMany() (to delete multiple documents)

findOneAndDelete() should be able to delete on _id.

like image 61
robertklep Avatar answered Oct 02 '22 23:10

robertklep