Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose delete multiple data at once

I have a big list of ids that I want to delete from mongodb from multiple models, the main idea is that I have the same id for a document in multiple schemas and I would like to delete a document from each model. I am doing it like this:

_.each(wrongList, function(item) {
        UPUSTP.find({id: item.id}).remove(function(err) {
            if (err)
                console.log("Error while deleting " + err.message);
        })

        UPUANAM.find({id: item.id}).remove(function(err) {
            if (err)
                console.log("Error while deleting " + err.message);
        })

        UPUEXE.find({id: item.id}).remove(function(err) {
            if (err)
                console.log("Error while deleting " + err.message);
        })

        UPUEXO.find({id: item.id}).remove(function(err) {
            if (err)
                console.log("Error while deleting " + err.message);
        })

        UPUPROC.find({id: item.id}).remove(function(err) {
            if (err)
                console.log("Error while deleting " + err.message);
        })
    })

The problem is that I have 14000+ ids in the wrongList and the query works but it takes a lot of time to finish... how can I increase the time of the remove? Can I remove in batch or something like that?

like image 921
exilonX Avatar asked Feb 23 '15 10:02

exilonX


People also ask

How to delete multiple records in Mongoose?

The deleteMany() function is how you can delete multiple documents from a collection using Mongoose. It takes up to two parameters: condition, what a document should contain to be eligible for deletion. You can omit this property to delete all documents in the model.

How to delete all data in Mongoose?

Mongoose | deleteMany() Function The deleteMany() function is used to delete all of the documents that match conditions from the collection. This function behaves like the remove() function but it deletes all documents that match conditions regardless of the single option.

What does deleteMany return in mongoose?

The deleteMany() method returns an object that contains three fields: n – number of matched documents. ok – 1 if the operation was successful. deletedCount – number of deleted documents.


1 Answers

I think that you could use $in operator of mongodb.

http://docs.mongodb.org/manual/reference/operator/query/in/

Something like:

UTUSTP.remove({_id: {$in: wronglist}}, function(){...}); // and so on
like image 77
Tiziano Rossi Avatar answered Sep 22 '22 23:09

Tiziano Rossi