Reputation: 63647
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?
Upvotes: 5
Views: 4362
Reputation: 64318
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}})
Upvotes: 6
Reputation: 2318
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})
Upvotes: 0