Question

How can we batch delete a number of documents using PyMongo?

If we start off with a list of docs,

docs = list( db.animals.find({'color':'red'}) )

Doing the following does not actually remove anything from the collection!

toRemove = [x['_id'] for x in docs]
db.animals.remove(toRemove)

What is the proper way of batch removing?

Was it helpful?

Solution

Simply use remove the same way you use find.

If the following line returns the records to be removed:

db.animals.find({'color':'red'})

then this will remove them:

db.animals.remove({'color':'red'})

If you already have a list of IDs to remove, you can remove with a filter on the _id, using the $in operator, like this:

db.animals.remove({'_id': {'$in': idsToRemove}})

OTHER TIPS

While some helper method to remove an array of documents may exist that I am unaware of, I would say the best and most explicit way is to use a loop:

for docId in toRemove:
    db.animals.remove({'_id':docId})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top