Retrieving a single record using PyMongo

Retrieving a single record is a common operation in any system with the CRUD (Create Read Update Delete) functionality.

Getting ready

PyMongo has a method that allows us to easily query a single record using zero or more criteria: find_one().

How to do it…

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.pythonbicookbook
accidents = db.accidents
# Find the first document in the collection
accidents.find_one()
# Find the first document in the collection where the accident happened on a Sunday
accidents.find_one({"Day_of_Week": 1})

How it works…

The find_one() method returns a single document—the first one it finds—based on the criteria provided. If there are multiple records ...

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.