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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With