how do I delete a document during iteration (using a cursor)?
db.users.find().forEach(function(myDoc) {
print( "user: " + myDoc.name );
// now I'm done with it
myDoc.remove(); // <-- this doesn't work
} );
is there a way to do it without having to do a separate search?
db.users.find().forEach(function(myDoc) {
print( "user: " + myDoc.name );
// now I'm done with it
db.users.findOneAndDelete(myDoc); // <-- this does work
} );
while the later does work, it seems like doing a search after already having the document would significantly slow down the process. (Am I wrong?)
You can first search objects and keep _ids in an array. And then use following code to remove all the elements once.
db.users.deleteMany(
{ "_id": {$in:idArray} },
function(err, results) {
}
);
EDIT
I found a bulk approach to do that.
var bulk = db.users.initializeUnorderedBulkOp();
bulk.find( { "_id": {$in:idArray} }).remove();
bulk.execute();
according to my experiance, you can reduce the execution time more than 10 time faster if you use bulk operations since it reduces IO operations.
You can use findAndModify
. Read more about it here
db.collection.findAndModify({
query: <document>,
remove: <boolean>
});
This function will return the deleted document, which you can use to print. You can loop it until no more documents are left.
EDIT:
Another approach you can take is using find
and bulkWrite(deleteMany)
.
First find and print all the docs. Then delete them using a bulkWrite operation.
db.users.find().forEach(function(myDoc) {
print( "user: " + myDoc.name );
});
//This is much faster than your current approach of
//finding and deleting singe documents
db.users.bulkWrite([
{
removeMany: <query>
}
]);
bulkWrite() - MongoDB
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