Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb + Node.js: delete multiple documents and return them

I'm using the below code to delete multiple documents at once:

db.collection('testcollection').deleteMany({
    id: {
        $in: ['1', '2', '3']
    }
}, function (error, response) {
    // ...
});

Is there a way to delete and return all the deleted documents in one go?

NOTE: I'm looking for multiple delete and multiple return, which is different than this question: How to get removed document in MongoDB?

like image 519
evilReiko Avatar asked Nov 28 '16 12:11

evilReiko


People also ask

How do I delete multiple files in MongoDB Nodejs?

You can delete multiple documents in a collection at once using the collection. deleteMany() method. Pass a query document to the deleteMany() method to specify a subset of documents in the collection to delete.

How do I delete a file in MongoDB node JS?

To delete a record, or document as it is called in MongoDB, we use the deleteOne() method. The first parameter of the deleteOne() method is a query object defining which document to delete.

How do I remove all files from a collection in MongoDB?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.


1 Answers

Unfortunately, deleteMany() passes only the error and deleteWriteOpResult to your callback so no actual documents are passed.

This is not just with Node.js - this is how actually db.collection.deleteMany works in Mongo:

Returns: A document containing:

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled

  • deletedCount containing the number of deleted documents

You have to do it with two requests, but you can abstract it away in a single function - e.g. if you're using the native Mongo driver you can write something like this:

function getAndDelete(collectionName, filter, callback) {
  var collection = db.collection(collectionName);
  collection.find(filter, function (err, data) {
    if (err) {
      callback(err);
    } else {
      collection.deleteMany(filter, function (err, r) {
        if (err) {
          callback(err);
        } else {
          callback(null, data);
        }
      });
    }
  });
}

that you can call with:

getAndDelete('testcollection', {
    id: {
        $in: ['1', '2', '3']
    }
}, function (error, response) {
    // ...
});

This code is not tested but just to give you an idea where to start from.

Note: there used to be findAndRemove() but it's been deprecated.

like image 174
rsp Avatar answered Sep 28 '22 07:09

rsp