Deleting a single record using pymongo

Sometimes, you just need to delete a record. That's easy with the delete_one() method.

Getting ready

As we've seen in the previous recipes, the first thing to do is to create a filter to find the record to delete.

How to do it…

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.pythonbicookbook
customers = db.customers
result = customers.delete_one({
'first_name': 'Bob',
'last_name': 'Smith' })
print(result.deleted_count)

How it works…

Given a filter, delete_one() deletes the first record that matches the filter. We then print out the count of records deleted to ensure that only one record was deleted.

Get Python Business Intelligence Cookbook 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.