Remove multiple documents from mongo in a single q

2019-01-07 13:53发布

问题:

I have a list of mongo '_id' which I want to delete. Currently I am doing this

# inactive_users -->  list of inactive users 
for item in inactive_users:
    db.users.remove({'_id' : item})

but my problem is the list is too huge... (it might go 100,000 +). So querying for every item in list will only increase the load on server. Is their a way to pass the entire list in mongo query so that I dont have to fire query again and again.

Thank you

回答1:

db.users.remove({'_id':{'$in':inactive_users}})


回答2:

List them all and use $in operator:

db.users.remove({_id:{$in:[id1, id2, id3, ... ]}})


回答3:

You need to pass the ids in a specific format using ObjectId():

db.users.remove({_id: {$in: [ObjectId('Item1'), ObjectId('Item2'), ObjectId('Item2')]}});

Remove doesn't accept integer - you have to use ObjectId instance with _id format as a string.



回答4:

var collection = db.users;
var usersDelete = [];
var ObjectID = req.mongo.ObjectID;   //req is request from express

req.body.forEach(function(item){     //req.body => [{'_id' : ".." , "name" : "john"}]
    usersDelete.push(new ObjectID(item._id));
});

collection.remove({'_id':{'$in': usersDelete}},function(){
    //res.json(contatos);
});