evilReiko evilReiko - 9 days ago 6
Node.js Question

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?

rsp rsp
Answer

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.