Navigation

Find or Query Data with PyMongo

Overview

You can use the find() method to issue a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection.

Queries can return all documents in a collection or only the documents that match a specified filter or criteria. You can specify the filter or criteria in a document and pass as a parameter to the find() method.

The find() method returns query results in a cursor, which is an iterable object that yields documents.

Prerequisites

The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset.

From a Python Shell or IDLE, use MongoClient to connect to the running mongod instance, and switch to the test database.

from pymongo import MongoClient

client = MongoClient()
db = client.test

Query for All Documents in a Collection

To return all documents in a collection, call the find() method without a criteria document. For example, the following operation queries for all documents in the restaurants collection.

cursor = db.restaurants.find()

Iterate the cursor and print the documents.

for document in cursor:
    print(document)

The result set contains all documents in the restaurants collection.

Specify Equality Conditions

The query condition for an equality match on a field has the following form:

{ <field1>: <value1>, <field2>: <value2>, ... }

If the <field> is in an embedded document or an array, use dot notation to access the field.

Query by a Top Level Field

The following operation finds documents whose borough field equals "Manhattan".

cursor = db.restaurants.find({"borough": "Manhattan"})

Iterate the cursor and print the matching documents.

for document in cursor:
    print(document)

The result set includes only the matching documents.

Query by a Field in an Embedded Document

To specify a condition on a field within an embedded document, use the dot notation. Dot notation requires quotes around the whole dotted field name. The following operation specifies an equality condition on the zipcode field in the address embedded document.

cursor = db.restaurants.find({"address.zipcode": "10075"})

Iterate the cursor and print the matching documents.

for document in cursor:
    print(document)

The result set includes only the matching documents.

For more information on querying on fields within an embedded document, see Query on Embedded/Nested Documents.

Query by a Field in an Array

The grades array contains embedded documents as its elements. To specify a condition on a field in these documents, use the dot notation. Dot notation requires quotes around the whole dotted field name. The following queries for documents whose grades array contains an embedded document with a field grade equal to "B".

cursor = db.restaurants.find({"grades.grade": "B"})

Iterate the cursor and print the matching documents.

for document in cursor:
    print(document)

The result set includes only the matching documents.

For more information on querying on arrays, such as specifying multiple conditions on array elements, see Query an Array and $elemMatch.

Specify Conditions with Operators

MongoDB provides operators to specify query conditions, such as comparison operators. Although there are some exceptions, such as the $or and $and conditional operators, query conditions using operators generally have the following form:

{ <field1>: { <operator1>: <value1> } }

For a complete list of the operators, see query operators.

Greater Than Operator ($gt)

Query for documents whose grades array contains an embedded document with a field score greater than 30.

cursor = db.restaurants.find({"grades.score": {"$gt": 30}})

Iterate the cursor and print the matching documents.

for document in cursor:
    print(document)

The result set includes only the matching documents.

Less Than Operator ($lt)

Query for documents whose grades array contains an embedded document with a field score less than 10.

cursor = db.restaurants.find({"grades.score": {"$lt": 10}})

Iterate the cursor and print the matching documents.

for document in cursor:
    print(document)

The result set includes only the matching documents.

Combine Conditions

You can combine multiple query conditions in logical conjunction (AND) and logical disjunctions (OR).

Logical AND

You can specify a logical conjunction (AND) for a list of query conditions by separating the conditions with a comma in the conditions document.

cursor = db.restaurants.find({"cuisine": "Italian", "address.zipcode": "10075"})

Iterate the cursor and print the matching documents.

for document in cursor:
    print(document)

The result set includes only the documents that matched all specified criteria.

Logical OR

You can specify a logical disjunction (OR) for a list of query conditions by using the $or query operator.

cursor = db.restaurants.find(
    {"$or": [{"cuisine": "Italian"}, {"address.zipcode": "10075"}]})

Iterate the cursor and print the matching documents.

for document in cursor:
    print(document)

The result set includes only the documents that match either conditions.

Sort Query Results

To specify an order for the result set, append the sort() method to the query. Pass to sort() method a document which contains the field(s) to sort by and the corresponding sort type, e.g. pymongo.ASCENDING for ascending and pymongo.DESCENDING for descending.

To sort by multiple keys, pass a list of keys and sort type pairs. For example, the following operation returns all documents in the restaurants collection, sorted first by the borough field in ascending order, and then, within each borough, by the "address.zipcode" field in ascending order:

import pymongo
cursor = db.restaurants.find().sort([
    ("borough", pymongo.ASCENDING),
    ("address.zipcode", pymongo.ASCENDING)
])

Iterate the cursor and print the matching documents.

for document in cursor:
    print(document)

The operation returns the results sorted in the specified order.

Additional Information

In the PyMongo documentation, see find(), Cursor, and sort().

In the MongoDB Manual, see also Query Documents tutorial, Projection tutorial, Query and Projection Operators reference, and Cursor Methods.