Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to batch delete records using PyMongo

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?

like image 411
Nyxynyx Avatar asked Jan 16 '14 04:01

Nyxynyx


People also ask

How do you delete data on PyMongo?

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.

How do I remove all data from a collection in MongoDB?

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.

How do you delete a record in MongoDB using Python?

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.


1 Answers

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}})
like image 179
shx2 Avatar answered Sep 22 '22 17:09

shx2