O'Reilly logo

MongoDB and Python by Niall O'Higgins

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading, Counting, and Sorting Documents in a Collection

In many situations, you only want to retrieve a single document from a collection. This is especially true when documents in your collection are unique on some property. A good example of this is a users collection, where each username is guaranteed unique.

# Assuming we already have a database handle in scope named dbh
# find a single document with the username "janedoe".
user_doc = dbh.users.find_one({"username" : "janedoe"})
if not user_doc:
    print "no document found for username janedoe"

Notice that find_one() will return None if no document is found.

Now imagine you wish to find all documents in the users collection which have a firstname property set to “jane” and print out their email addresses. MongoDB will return a Cursor object for us, to stream the results. PyMongo handles result streaming as you iterate, so if you have a huge number of results they are not all stored in memory at once.

# Assuming we already have a database handle in scope named dbh
# find all documents with the firstname "jane".
# Then iterate through them and print out the email address.
users = dbh.users.find({"firstname":"jane"})
for user in users:
    print user.get("email")

Notice in the above example that we use the Python dict class’ get method. If we were certain that every single result document contained the “email” property, we could have used dictionary access instead.

for user in users:
    print user["email"]

If you only wish to retrieve a subset ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required