45

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

Anurag Sharma
  • 4,839
  • 13
  • 59
  • 101

5 Answers5

106
db.users.deleteMany({'_id':{'$in':inactive_users}})
Shadoweb
  • 5,812
  • 1
  • 42
  • 55
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
23

List them all and use $in operator:

db.users.remove({_id:{$in:[id1, id2, id3, ... ]}})
Yevgeniy Anfilofyev
  • 4,827
  • 25
  • 27
  • 5
    If the list is really 100 000+ items huge, then you may want to break it up into batches of a few hundred per call. – Sean Reilly Sep 02 '13 at 06:44
8

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.

julien bouteloup
  • 3,022
  • 22
  • 16
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);
});
3

I had the same question and ran across these answers but it seems the MongoDB manual is recommending deleteMany instead of remove. deleteMany returns the delete count as well as an acknowledgement of the write concern (if the operation succeeded).

const ids = [id1, id2, id3...];
const query = { _id: { $in: ids} };
dbo.collection("users").deleteMany(query, function (err, obj) {
    if (err) throw err;
});

Or with an arrow function:

const ids = [id1, id2, id3...];
const query = { _id: { $in: ids} };
dbo.collection("users").deleteMany(query, (err, obj) => {
    if (err) throw err;
});

Or better yet, with a promise:

const ids = [id1, id2, id3...];
const query = { _id: { $in: ids} };
dbo.collection("users").deleteMany(query)
.then(result => {
    console.log("Records Deleted");
    console.log(JSON.stringify(result));
    //for number removed...
    console.log("Removed: " + result["n"]);
})
.catch(err => {
    console.log("Error");
    console.log(err);
});
docb45
  • 274
  • 3
  • 9