Deleting Documents from a Collection

If you wish to permanently delete documents from a collection, it is quite easy to do so. The PyMongo Collection object has a remove() method. As with reads and updates, you specify which documents you want to remove by way of a document spec. For example, to delete all documents from the users collection with a score of 1, you would use the following code:

# Delete all documents in user collection with score 1
dbh.users.remove({"score":1}, safe=True)

Note that the remove() method takes a safe parameter. As mentioned in the earlier section “Write to a Collection Safely and Synchronously”, it is recommended to set the safe parameter to True on write methods to ensure the operation has completed. It is also worth noting that remove() will not raise any exception or error if no documents are matched.

Finally, if you wish to delete all documents in a collection, you can pass None as a parameter to remove():

# Delete all documents in user collection
dbh.users.remove(None, safe=True)

Clearing a collection with remove() differs from dropping the collection via drop_collection() in that the indexes will remain intact.

Get MongoDB and Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.