Docs Menu
Docs Home
/ / /
PyMongo

Read Data from MongoDB

On this page

  • Overview
  • Sample Application
  • Find One
  • Find Multiple
  • Count Documents in a Collection
  • Count Documents Returned from a Query
  • Estimated Document Count
  • Retrieve Distinct Values
  • Monitor Data Changes

On this page, you can see copyable code examples that show common methods you can use to retrieve documents with PyMongo.

Tip

To learn more about any of the methods shown on this page, see the link provided in each section.

To use an example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as <connection string URI>, with the relevant values for your MongoDB deployment.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Ensure you have PyMongo installed.

  2. Copy the following code and paste it into a new .py file.

  3. Copy a code example from this page and paste it on the specified lines in the file.

1import pymongo
2from pymongo import MongoClient
3
4try:
5 uri = "<connection string URI>"
6 client = MongoClient(uri)
7
8 database = client["<database name>"]
9 collection = database["<collection name>"]
10
11 # start example code here
12
13 # end example code here
14
15 client.close()
16
17except Exception as e:
18 raise Exception(
19 "The following error occurred: ", e)
results = collection.find_one({ "<field name>" : "<value>" })
print(results)

To learn more about the find_one() method, see Find One Document in the Retrieve Data guide.

results = collection.find({ "<field name>" : "<value>" })
for document in results:
print(document)

To learn more about the find() method, see Find Multiple Documents in the Retrieve Data guide.

count = collection.count_documents({})
print(count)

To learn more about the count_documents() method, see the Retrieve an Accurate Count guide.

count = collection.count_documents({ "<field name>": "<value>" })
print(count)

To learn more about the count_documents() method, see the Retrieve an Accurate Count guide.

count = collection.estimated_document_count()
print(count)

To learn more about the estimated_document_count() method, see the Retrieve an Estimated Count guide.

results = collection.distinct("<field name>")
for document in results:
print(document)

To learn more about the distinct() method, see the Retrieve Distinct Field Values guide.

with collection.watch() as stream:
for change in stream:
print(change)

To learn more about the watch() method, see the Monitor Data Changes guide.

Back

Transactions