Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing document from collection during find

Tags:

mongodb

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?)

like image 295
Daniel Avatar asked Apr 21 '16 17:04

Daniel


2 Answers

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.

like image 200
Lakmal Vithanage Avatar answered Oct 01 '22 07:10

Lakmal Vithanage


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

like image 41
ayushgp Avatar answered Oct 01 '22 08:10

ayushgp