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?
To delete one document, we use the delete_one() method. The first parameter of the delete_one() method is a query object defining which document to delete. Note: If the query finds more than one document, only the first occurrence is deleted.
To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.
To delete documents from a collection of MangoDB, you can delete documents from a collections using the methods delete_one() and delete_many() methods. These methods accept a query object specifying the condition for deleting documents. The detele_one() method deletes a single document, in case of a match.
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}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With