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 found, find_one() will return the first match. If only one record is found, that will be returned.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset