For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Logging and Monitoring

On this page, you can see copyable code examples that show common methods you can use to monitor and log events 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.

import pymongofrom pymongo import MongoClient try: uri = "<connection string URI>" client = MongoClient(uri) database = client["<database name>"] collection = database["<collection name>"] # start example code here # end example code here client.close() except Exception as e: raise Exception( "The following error occurred: ", e)
with collection.watch() as stream: for change in stream: print(change)

To learn more about the watch() method, see the Monitor Data with Change Streams guide.

Rate this page