Retrieving multiple records using PyMongo

In order to produce a list view on a web page, or to pull more than a single record out of MongoDB, say, for analysis, you will need to query for multiple records.

Getting ready

PyMongo provides a find() function that we can use to search for multiple documents that match a given criteria, returning a cursor instance that we can iterate over.

How to do it…

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.pythonbicookbook
accidents = db.accidents
# Retrieve all records where the accident happened on a Friday
data = accidents.find({"Day_of_Week": 7})
# Show a count for the result
data.count() # returns 896218

How it works…

The find() function is a powerful method for filtering a result set to get only the records that you want. You can search on a single field, as we have in this recipe, or search on multiple fields. In addition, you can limit your results to a subset of the available fields using the projection argument. You can also limit the number of results provided in order to get a top count.

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

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