### Create Project Directory (Windows) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started Creates a new directory for the PyMongo project on Windows systems. This involves creating a folder and an empty Python file to house the application code. ```bash mkdir pymongo-quickstart cd pymongo-quickstart type nul > quickstart.py ``` -------------------------------- ### Activate Virtual Environment (Windows) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started Sets up and activates a Python virtual environment on Windows. This isolates project dependencies, ensuring compatibility and preventing conflicts with other Python projects. ```bash python3 -m venv venv . venv\Scripts\activate ``` -------------------------------- ### Install PyMongo Driver Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started Installs the PyMongo driver using pip within an activated virtual environment. PyMongo is the official Python driver for MongoDB, enabling applications to interact with MongoDB databases. ```bash python3 -m pip install pymongo ``` -------------------------------- ### Create Project Directory (macOS/Linux) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started Creates a new directory for the PyMongo project on macOS or Linux systems. This is the initial step in setting up a new Python application that will use PyMongo. ```bash mkdir pymongo-quickstart cd pymongo-quickstart touch quickstart.py ``` -------------------------------- ### Activate Virtual Environment (macOS/Linux) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started Sets up and activates a Python virtual environment on macOS or Linux. This isolates project dependencies, ensuring compatibility and preventing conflicts with other Python projects. ```bash python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Sample Application Structure for PyMongo Monitoring Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/monitoring-and-logging A foundational Python script to integrate PyMongo monitoring examples. It sets up a MongoClient connection and includes placeholders for inserting specific monitoring code. Ensure PyMongo is installed and replace placeholders like '' before use. ```python import pymongo from pymongo import MongoClient try: uri = "" client = MongoClient(uri) database = client[""] collection = database[""] # start example code here # end example code here client.close() except Exception as e: raise Exception( "The following error occurred: ", e) ``` -------------------------------- ### Synchronous MongoDB Connection and Query with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started Establishes a synchronous connection to MongoDB using PyMongo, retrieves a specific movie document by its title from the 'movies' collection in the 'sample_mflix' database, and prints the document. Includes basic error handling for connection and query operations. Requires a valid MongoDB connection string URI. ```python from pymongo import MongoClient uri = "" client = MongoClient(uri) try: database = client.get_database("sample_mflix") movies = database.get_collection("movies") # Query for a movie that has the title 'Back to the Future' query = { "title": "Back to the Future" } movie = movies.find_one(query) print(movie) client.close() except Exception as e: raise Exception("Unable to find the document due to the following error: ", e) ``` -------------------------------- ### Install PyMongoExplain Library Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/aggregation Installs the `pymongoexplain` library using pip, which is a dependency for explaining aggregation operations in MongoDB with Python. ```sh python3 -m pip install pymongoexplain ``` -------------------------------- ### Connect to MongoDB (Synchronous) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect Establishes a synchronous connection to a MongoDB deployment using PyMongo. Requires the PyMongo library to be installed. Takes a MongoDB connection URI as input and returns a MongoClient instance. ```python from pymongo import MongoClient try: # start example code here uri = "mongodb://localhost:27017/" client = MongoClient(uri) # end example code here client.admin.command("ping") print("Connected successfully") # other application code client.close() except Exception as e: raise Exception( "The following error occurred: ", e) ``` ```python uri = "mongodb://localhost:27017/" client = MongoClient(uri) ``` ```python uri = "" client = MongoClient(uri, server_api=pymongo.server_api.ServerApi( version="1", strict=True, deprecation_errors=True)) ``` ```python uri = "mongodb://:/?replicaSet=" client = MongoClient(uri) ``` -------------------------------- ### Explain Aggregation with PyMongoExplain Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/aggregation Runs an aggregation pipeline and retrieves its explanation using the `pymongoexplain` library. This method requires the `pymongoexplain` library to be installed. ```python # Define an aggregation pipeline with a match stage and a group stage pipeline = [ { "$match": { "cuisine": "Bakery" } }, { "$group": { "_id": "$borough", "count": { "$sum": 1 } } } ] # Execute the operation and print the explanation result = ExplainableCollection(collection).aggregate(pipeline) print(result) ``` -------------------------------- ### Server Selection in PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect Illustrates how to specify a server selection function within the connection string for MongoDB using PyMongo. This example is provided for both synchronous and asynchronous MongoClient instances. ```python client = pymongo.MongoClient("mongodb://:@:", server_selector=) ``` ```python client = pymongo.AsyncMongoClient("mongodb://:@:", server_selector=) ``` -------------------------------- ### Asynchronous MongoDB Connection and Query with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started Establishes an asynchronous connection to MongoDB using PyMongo's AsyncMongoClient, retrieves a specific movie document by its title from the 'movies' collection in the 'sample_mflix' database, and prints the document. Includes basic error handling. Requires a valid MongoDB connection string URI. This is suitable for non-blocking I/O operations. ```python import asyncio from pymongo import AsyncMongoClient async def main(): uri = "" client = AsyncMongoClient(uri) try: database = client.get_database("sample_mflix") movies = database.get_collection("movies") # Query for a movie that has the title 'Back to the Future' query = { "title": "Back to the Future" } movie = await movies.find_one(query) print(movie) await client.close() except Exception as e: raise Exception("Unable to find the document due to the following error: ", e) # Run the async function asyncio.run(main()) ``` -------------------------------- ### Stable API Configuration in PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect Demonstrates how to configure Stable API settings for a MongoDB connection using the PyMongo driver. This example includes the necessary import and shows configuration for both synchronous and asynchronous clients. ```python from pymongo.server_api import ServerApi client = pymongo.MongoClient("mongodb://:@", server_api=ServerApi("")) ``` ```python from pymongo.server_api import ServerApi client = pymongo.AsyncMongoClient("mongodb://:@", server_api=ServerApi("")) ``` -------------------------------- ### Set Read Preference for Command Execution (Python) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Demonstrates how to explicitly set a read preference for a command execution using the `read_preference` parameter with the `command()` method. This example sets the read preference to `Secondary` for the 'hello' command. ```python from pymongo.read_preferences import Secondary database = client.get_database("my_db") hello = database.command("hello", read_preference=Secondary()) print(hello) ``` -------------------------------- ### Create Geospatial Index in Python Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Demonstrates creating a 2dsphere geospatial index on the 'location.geo' field in MongoDB using PyMongo. It includes an example of performing a geospatial query to find theaters within a specified radius of a given point. ```python from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") database = client["sample_mflix"] collection = database["theaters"] try: # Create 2dsphere index for geospatial queries index_name = collection.create_index([("location.geo", "2dsphere")]) print(f"Created geospatial index: {index_name}") # Query theaters near a location query = { "location.geo": { "$near": { "$geometry": { "type": "Point", "coordinates": [-118.3, 34.0] }, "$maxDistance": 5000 # 5km radius } } } results = collection.find(query).limit(5) print("\nTheaters within 5km:") for theater in results: print(f" {theater.get('location', {}).get('address', {}).get('city', 'Unknown')}") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Configure SCRAM-SHA-1 Authentication in PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security Shows how to configure SCRAM-SHA-1 authentication for MongoDB connections using PyMongo. This method uses the MongoClient constructor or a connection string, specifying authentication details. Examples are provided for both synchronous and asynchronous client instantiation. ```python client = pymongo.MongoClient("mongodb://:", username="", password="", authSource="", authMechanism="SCRAM-SHA-1") ``` ```python uri = ("mongodb://:" "@:/?" "authSource=" "&authMechanism=SCRAM-SHA-1") client = pymongo.MongoClient(uri) ``` ```python client = pymongo.AsyncMongoClient("mongodb://:", username="", password="", authSource="", authMechanism="SCRAM-SHA-1") ``` ```python uri = ("mongodb://:" "@:/?" "authSource=" "&authMechanism=SCRAM-SHA-1") client = pymongo.AsyncMongoClient(uri) ``` -------------------------------- ### Count Documents in MongoDB with PyMongo (Python) Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Provides examples of counting documents in a MongoDB collection using PyMongo. It covers counting all documents, counting with specific filters, and using `estimated_document_count` for a faster, approximate count. Includes error handling and client connection closure. ```python from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") database = client["sample_mflix"] collection = database["movies"] try: # Count all documents in collection total_count = collection.count_documents({}) print(f"Total movies: {total_count}") # Count documents matching a query action_movies = collection.count_documents({"genres": "Action"}) print(f"Action movies: {action_movies}") # Count with complex filter recent_popular = collection.count_documents({ "year": {"$gte": 2010}, "imdb.rating": {"$gte": 7.5} }) print(f"Recent popular movies: {recent_popular}") # Estimated count (faster but less accurate) estimated = collection.estimated_document_count() print(f"Estimated total: {estimated}") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Type Hinting Database with TypedDict (Python) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/databases-collections Demonstrates how to use Python's `TypedDict` for defining schema for documents within a MongoDB database. This enhances type checking and code completion, particularly for applications using Python 3.8+. Includes synchronous and asynchronous client examples. ```python from typing import TypedDict from pymongo import MongoClient from pymongo.database import Database class Movie(TypedDict): name: str year: int client: MongoClient = MongoClient() database: Database[Movie] = client["test_database"] ``` ```python from typing import TypedDict from pymongo import AsyncMongoClient from pymongo.asynchronous.database import Database class Movie(TypedDict): name: str year: int client: AsyncMongoClient = AsyncMongoClient() database: Database[Movie] = client["test_database"] ``` -------------------------------- ### Create Wildcard Index on Field in Python Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/indexes Creates an ascending wildcard index on the 'location' field and its nested values, suitable for dynamic schemas. The '$**' syntax is used to match arbitrary fields. Both synchronous and asynchronous PyMongo examples are included. ```python movies.create_index({ "location.$**": pymongo.ASCENDING }) ``` ```python await movies.create_index({ "location.$**": pymongo.ASCENDING }) ``` -------------------------------- ### Create Text Index in Python Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Shows how to create a text index on multiple fields ('plot' and 'title') in MongoDB using PyMongo for full-text search capabilities. It includes an example of performing a text search query and retrieving matching documents. ```python from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") database = client["sample_mflix"] collection = database["movies"] try: # Create text index for full-text search index_name = collection.create_index([("plot", "text"), ("title", "text")]) print(f"Created text index: {index_name}") # Perform text search query = {"$text": {"$search": "time travel adventure"}} results = collection.find(query).limit(5) print("\nMovies matching 'time travel adventure':") for movie in results: print(f" {movie.get('title', 'Unknown')}") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Client-Side Timeout in PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect Provides an example of setting a client-side timeout for operations in PyMongo using the `timeout()` method within a `with` statement. This helps limit the execution time of MongoDB operations on the client side. ```python with pymongo.timeout(): # perform operations here ``` -------------------------------- ### Synchronous Aggregation Pipeline with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/aggregation Executes a synchronous aggregation pipeline using PyMongo. This example filters documents for 'Bakery' cuisine and then groups them by borough, counting the occurrences in each. It requires a PyMongo collection object. ```python # Define an aggregation pipeline with a match stage and a group stage pipeline = [ { "$match": { "cuisine": "Bakery" } }, { "$group": { "_id": "$borough", "count": { "$sum": 1 } } } ] # Execute the aggregation aggCursor = collection.aggregate(pipeline) # Print the aggregated results for document in aggCursor: print(document) ``` -------------------------------- ### Python PyMongo: Connect Async using AssumeRole Request (Connection String) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security Provides an example of connecting to MongoDB asynchronously using a connection string with AWS IAM `AssumeRole` authentication. This method incorporates percent-encoded credentials and session token for connection details. Requires the `pymongo` library. ```python uri = ("mongodb://:" "" "@:/ ?" "authMechanismProperties=AWS_SESSION_TOKEN:" "&authMechanism=MONGODB-AWS") client = pymongo.AsyncMongoClient(uri) ``` -------------------------------- ### Authenticate with MONGODB-AWS using credentials in PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security Shows how to authenticate to MongoDB using the MONGODB-AWS authentication mechanism with AWS IAM credentials in PyMongo. It includes examples for both MongoClient and connection string configurations. ```python client = pymongo.MongoClient("mongodb://:", username="", password="", authMechanism="MONGODB-AWS") ``` ```python uri = ("mongodb://:" "" "@:/?" "&authMechanism=MONGODB-AWS") client = pymongo.MongoClient(uri) ``` ```python client = pymongo.AsyncMongoClient("mongodb://:", username="", password="", authMechanism="MONGODB-AWS") ``` ```python uri = ("mongodb://:" "" "@:/?" "&authMechanism=MONGODB-AWS") client = pymongo.AsyncMongoClient(uri) ``` -------------------------------- ### Enable TLS with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security Demonstrates how to enable Transport Layer Security (TLS) for MongoDB connections using PyMongo. This can be achieved either by setting the `tls=True` parameter directly in MongoClient or by appending `?tls=true` to the connection string. Examples are provided for both synchronous and asynchronous clients. ```python client = pymongo.MongoClient("mongodb://:@", tls=True) ``` ```python client = pymongo.MongoClient("mongodb://:@:?tls=true") ``` ```python client = pymongo.AsyncMongoClient("mongodb://:@", tls=True) ``` ```python client = pymongo.AsyncMongoClient("mongodb://:@:?tls=true") ``` -------------------------------- ### Query Using Multikey Index with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/indexes Demonstrates how to query a MongoDB collection using a previously created multikey index on the 'cast' field. This example shows filtering documents where the 'cast' array contains a specific value. ```python query = { "cast": "Viola Davis" } cursor = movies.find(query) ``` -------------------------------- ### Asynchronous Aggregation Pipeline with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/aggregation Executes an asynchronous aggregation pipeline using PyMongo. Similar to the synchronous version, this example filters for 'Bakery' cuisine and groups by borough, counting results. It requires an asynchronous PyMongo collection object and must be run within an async context. ```python # Define an aggregation pipeline with a match stage and a group stage pipeline = [ { "$match": { "cuisine": "Bakery" } }, { "$group": { "_id": "$borough", "count": { "$sum": 1 } } } ] # Execute the aggregation aggCursor = await collection.aggregate(pipeline) # Print the aggregated results async for document in aggCursor: print(document) ``` -------------------------------- ### Create Compound Index in Python Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Illustrates creating a compound index on multiple fields in MongoDB using PyMongo. This example creates an index on 'type', 'genre', and 'year' with specified sort orders (ascending for type and genre, descending for year). It also shows a query that can utilize this compound index. ```python import pymongo from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") database = client["sample_mflix"] collection = database["movies"] try: # Create compound index on multiple fields index_name = collection.create_index([ ("type", pymongo.ASCENDING), ("genre", pymongo.ASCENDING), ("year", pymongo.DESCENDING) ]) print(f"Created compound index: {index_name}") # Query that can use this index query = {"type": "movie", "genre": "Drama"} sort = [("type", 1), ("genre", 1), ("year", -1)] results = collection.find(query).sort(sort).limit(10) for movie in results: print(f" {movie.get('title', 'Unknown')}") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Specify CA File for TLS with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security Shows how to configure PyMongo to use a specific Certificate Authority (CA) file for TLS connections. This enhances security by ensuring the client trusts the server's certificate. The `tlsCAFile` parameter can be used with MongoClient, or the `tlsCAFile` option can be added to the connection string. Examples cover synchronous and asynchronous clients. ```python client = pymongo.MongoClient("mongodb://:@:", tls=True, tlsCAFile="/path/to/ca.pem") ``` ```python uri = "mongodb://:@:/?tls=true&tlsCAFile=/path/to/ca.pem" client = pymongo.MongoClient(uri) ``` ```python client = pymongo.AsyncMongoClient("mongodb://:@:", tls=True, tlsCAFile="/path/to/ca.pem") ``` ```python uri = "mongodb://::/?tls=true&tlsCAFile=/path/to/ca.pem" client = pymongo.AsyncMongoClient(uri) ``` -------------------------------- ### Example Search Results from PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/atlas-search This is a sample output of movie titles and their corresponding search scores returned by the PyMongo Atlas Search query. It shows a list of movies related to 'New York' that do not have 'Comedy' in their genres, ordered by relevance score. ```text {'title': 'New York, New York', 'score': 6.786379814147949} {'title': 'New York', 'score': 6.258603096008301} {'title': 'New York Doll', 'score': 5.381444931030273} {'title': 'Escape from New York', 'score': 4.719935417175293} {'title': 'Autumn in New York', 'score': 4.719935417175293} {'title': 'Sleepless in New York', 'score': 4.719935417175293} {'title': 'Gangs of New York', 'score': 4.719935417175293} {'title': 'Sherlock Holmes in New York', 'score': 4.203253746032715} {'title': 'New York: A Documentary Film', 'score': 4.203253746032715} {'title': 'An Englishman in New York', 'score': 4.203253746032715} ``` -------------------------------- ### Python PyMongo OIDC Auth for Azure (Sync & Async) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security Configure PyMongo's MongoClient and AsyncMongoClient for OIDC authentication with Azure environments. This involves defining a custom OIDC callback that uses Azure Identity's DefaultAzureCredential to fetch an access token. Ensure the `azure-identity` library is installed. ```python from pymongo import MongoClient from azure.identity import DefaultAzureCredential from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResult # define callback, properties, and MongoClient audience = "" client_id = "" class MyCallback(OIDCCallback): def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: credential = DefaultAzureCredential(managed_identity_client_id=client_id) token = credential.get_token(f"{audience}/.default").token return OIDCCallbackResult(access_token=token) properties = {"OIDC_CALLBACK": MyCallback()} client = MongoClient( "mongodb[+srv]://:", authMechanism="MONGODB-OIDC", authMechanismProperties=properties ) ``` ```python from pymongo import AsyncMongoClient from azure.identity import DefaultAzureCredential from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResult # define callback, properties, and MongoClient audience = "" client_id = "" class MyCallback(OIDCCallback): def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: credential = DefaultAzureCredential(managed_identity_client_id=client_id) token = credential.get_token(f"{audience}/.default").token return OIDCCallbackResult(access_token=token) properties = {"OIDC_CALLBACK": MyCallback()} client = AsyncMongoClient( "mongodb[+srv]://:", authMechanism="MONGODB-OIDC", authMechanismProperties=properties ) ``` -------------------------------- ### Python PyMongo: Connect Async using AWS Config File (Connection String) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security Provides an example of connecting to MongoDB asynchronously using a connection string with AWS IAM authentication, leveraging an AWS config file. Ideal for applications requiring asynchronous operations. Requires the `pymongo` library. ```python uri = "mongodb://:/?&authMechanism=MONGODB-AWS" client = pymongo.AsyncMongoClient(uri) ``` -------------------------------- ### Execute 'hello' Command Synchronously with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Demonstrates running the 'hello' database command using PyMongo's synchronous `command()` method. This method is useful for administrative tasks and diagnostics when a specific wrapper method is not available. It takes the command name and any arguments, returning the command's result. ```python database = client.get_database("my_db") hello = database.command("hello") print(hello) ``` -------------------------------- ### Create MongoDB Collections with Options (Python) Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Demonstrates how to create regular, capped, and time series collections in MongoDB using PyMongo. It shows how to specify options like size, max documents, and time series configurations. Includes error handling and closing the client connection. ```python from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") database = client["test_database"] try: # Create a regular collection database.create_collection("users") # Create a capped collection (fixed size) database.create_collection( "logs", capped=True, size=5242880, # 5MB max=5000 # max 5000 documents ) # Create a time series collection database.create_collection( "weather_data", timeseries={ "timeField": "timestamp", "metaField": "sensor_id", "granularity": "hours" } ) print("Collections created successfully") # List all collections collections = database.list_collection_names() print(f"Collections in database: {collections}") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Specify Compression Algorithms in PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect Demonstrates how to specify available compression algorithms (snappy, zstd, zlib) when connecting to MongoDB using PyMongo. This can be done via MongoClient options or within the connection string for both synchronous and asynchronous clients. ```python client = pymongo.MongoClient("mongodb://:@:", compressors = "snappy,zstd,zlib") ``` ```python uri = ("mongodb://:@:/?" "compressors=snappy,zstd,zlib") client = pymongo.MongoClient(uri) ``` ```python client = pymongo.AsyncMongoClient("mongodb://:@:", compressors = "snappy,zstd,zlib") ``` ```python uri = ("mongodb://:@:/?" "compressors=snappy,zstd,zlib") client = pymongo.AsyncMongoClient(uri) ``` -------------------------------- ### MongoClient with Document Type Hint Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Shows how to provide a type hint for the document structure within a MongoClient object to resolve type checker warnings about incompatible types. ```python from pymongo import MongoClient from typing import Dict, Any client: MongoClient[Dict[str, Any]] ``` -------------------------------- ### Explain Aggregation with Database Command Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/aggregation Runs an aggregation pipeline and retrieves its explanation by sending a database command to MongoDB. This method uses the `aggregate` command with the `explain=True` option. ```python # Define an aggregation pipeline with a match stage and a group stage pipeline = [ { $match: { cuisine: "Bakery" } }, { $group: { _id: "$borough", count: { $sum: 1 } } } ] # Execute the operation and print the explanation result = database.command("aggregate", "collection", pipeline=pipeline, explain=True) print(result) ``` -------------------------------- ### Insert Multiple Documents with PyMongo (Synchronous) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud Provides an example of inserting multiple documents into a MongoDB collection concurrently using the synchronous `insert_many()` method. It requires a list of document dictionaries. The output confirms if the insertions were acknowledged. ```python document_list = [ { "" : "" }, { "" : "" } ] result = collection.insert_many(document_list) print(result.acknowledged) ``` -------------------------------- ### Execute MongoDB Database Commands in Python Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Demonstrates how to execute various database commands like 'hello', 'dbStats', and 'collStats' using PyMongo. It shows how to retrieve connection information and collection statistics. Error handling is included for robustness. ```python from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") database = client["sample_mflix"] try: # Run hello command hello = database.command("hello") print(f"Connected to: {hello.get('me')}") print(f"Max BSON size: {hello.get('maxBsonObjectSize')}") # Run dbStats command stats = database.command("dbStats") print(f"\nDatabase: {stats['db']}") print(f"Collections: {stats['collections']}") print(f"Data size: {stats['dataSize']} bytes") print(f"Storage size: {stats['storageSize']} bytes") print(f"Indexes: {stats['indexes']}") # Run collStats command coll_stats = database.command("collStats", "movies") print(f"\nCollection 'movies' document count: {coll_stats['count']}") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Connect to Local MongoDB using PyMongo Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Establishes a connection to a local MongoDB instance using MongoClient, performs a ping to verify connectivity, inserts a document, and closes the connection. This is a fundamental step for any PyMongo application interacting with a local database. ```python from pymongo import MongoClient uri = "mongodb://localhost:27017/" client = MongoClient(uri) try: # Verify connection client.admin.command("ping") print("Successfully connected to MongoDB") # Access database and collection database = client["test_database"] collection = database["test_collection"] # Perform operations result = collection.insert_one({"name": "Alice", "age": 30}) print(f"Inserted document ID: {result.inserted_id}") finally: client.close() ``` -------------------------------- ### Connect to MongoDB (Asynchronous) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect Establishes an asynchronous connection to a MongoDB deployment using PyMongo's AsyncMongoClient. Requires the PyMongo library and asyncio. Takes a MongoDB connection URI as input and returns an AsyncMongoClient instance. ```python import asyncio from pymongo import AsyncMongoClient async def main(): try: # start example code here uri = "mongodb://localhost:27017/" client = AsyncMongoClient(uri) # end example code here await client.admin.command("ping") print("Connected successfully") # other application code await client.close() except Exception as e: raise Exception( "The following error occurred: ", e) asyncio.run(main()) ``` ```python uri = "mongodb://localhost:27017/" client = AsyncMongoClient(uri) ``` ```python uri = "" client = AsyncMongoClient(uri, server_api=pymongo.server_api.ServerApi( version="1", strict=True, deprecation_errors=True)) ``` ```python uri = "mongodb://:/?replicaSet=" client = AsyncMongoClient(uri) ``` -------------------------------- ### Execute 'hello' Command Asynchronously with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Shows how to execute the 'hello' database command asynchronously using PyMongo's `command()` method with the `await` keyword. This is suitable for non-blocking operations, allowing the application to perform other tasks while waiting for the command result. ```python database = client.get_database("my_db") hello = await database.command("hello") print(hello) ``` -------------------------------- ### Update One Document with PyMongo (Asynchronous) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud Provides an asynchronous example of updating a single document based on a filter using `await collection.update_one()`. This method takes a query filter and an update operation, returning the count of modified documents. ```python query_filter = { "" : "" } update_operation = { "$set" : { "" : "" } } result = await collection.update_one(query_filter, update_operation) print(result.modified_count) ``` -------------------------------- ### Count Documents in Collection (Python PyMongo) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud Counts the number of documents in a collection that match the query filter. This is useful for getting an estimate or an exact count of records. An empty filter `{}` will count all documents in the collection. Dependencies include the PyMongo driver. ```python count = collection.count_documents({}) print(count) ``` ```python count = await collection.count_documents({}) print(count) ``` -------------------------------- ### Typed Collection Initialization (Python) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/databases-collections Demonstrates how to initialize a PyMongo Collection with a generic type hint using `TypedDict` for document structure. This ensures type safety for documents within the collection. Supports both synchronous and asynchronous client connections. ```python from typing import TypedDict from pymongo import MongoClient from pymongo.collection import Collection class Movie(TypedDict): name: str year: int client: MongoClient = MongoClient() database = client["test_database"] collection: Collection[Movie] = database["test_collection"] ``` ```python from typing import TypedDict from pymongo import AsyncMongoClient from pymongo.asynchronous.collection import Collection class Movie(TypedDict): name: str year: int client: AsyncMongoClient = AsyncMongoClient() database = client["test_database"] collection: Collection[Movie] = database["test_collection"] ``` -------------------------------- ### Decode BSON to RawBSONDocument (Synchronous) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Decodes BSON documents returned by a command into RawBSONDocument instances using PyMongo's synchronous client. Requires specifying CodecOptions with RawBSONDocument. ```python from pymongo import MongoClient from bson.raw_bson import RawBSONDocument from bson import CodecOptions client: MongoClient = MongoClient() options = CodecOptions(RawBSONDocument) result = client.admin.command("ping", codec_options=options) ``` -------------------------------- ### Create MongoDB Collection in Python (Sync/Async) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/databases-collections Demonstrates creating a MongoDB collection explicitly using the `create_collection()` method. Supports both synchronous and asynchronous PyMongo operations. ```python database = client["test_database"] database.create_collection("example_collection") ``` ```python database = client["test_database"] await database.create_collection("example_collection") ``` -------------------------------- ### Update Atlas Search Index with PyMongo Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/indexes Updates an existing Atlas Search index definition. This method applies a new configuration to the specified index. Ensure the index name and definition are correct before execution. This example demonstrates updating a standard Atlas Search index. ```python new_index_definition = { "mappings": { "dynamic": False } } collection.update_search_index("my_index", new_index) ``` -------------------------------- ### Decode BSON to RawBSONDocument (Asynchronous) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Decodes BSON documents returned by a command into RawBSONDocument instances using PyMongo's asynchronous client. Requires specifying CodecOptions with RawBSONDocument. ```python from pymongo import AsyncMongoClient from bson.raw_bson import RawBSONDocument from bson import CodecOptions client: AsyncMongoClient = AsyncMongoClient() options = CodecOptions(RawBSONDocument) result = await client.admin.command("ping", codec_options=options) ``` -------------------------------- ### Decode BSON to TypedDict (Asynchronous) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Decodes BSON documents into instances of a specified TypedDict subclass using PyMongo's asynchronous client. Requires defining the TypedDict and passing it to CodecOptions. ```python from pymongo import AsyncMongoClient from bson.raw_bson import RawBSONDocument from bson import CodecOptions from typing import TypedDict class Movie(TypedDict): name: str year: int client: AsyncMongoClient = AsyncMongoClient() options: CodecOptions[Movie] = CodecOptions(Movie) result = await client.admin.command("ping", codec_options=options) ``` -------------------------------- ### Decode BSON to TypedDict (Synchronous) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Decodes BSON documents into instances of a specified TypedDict subclass using PyMongo's synchronous client. Requires defining the TypedDict and passing it to CodecOptions. ```python from pymongo import MongoClient from bson.raw_bson import RawBSONDocument from bson import CodecOptions from typing import TypedDict class Movie(TypedDict): name: str year: int client: MongoClient = MongoClient() options: CodecOptions[Movie] = CodecOptions(Movie) result = client.admin.command("ping", codec_options=options) ``` -------------------------------- ### Configure TLS/SSL Connection in Python with PyMongo Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Demonstrates how to establish a secure TLS/SSL connection to MongoDB using PyMongo. It includes parameters for enabling TLS, specifying the CA file, and providing client certificate and key files. ```python from pymongo import MongoClient # Enable TLS with CA certificate client = MongoClient( "mongodb://hostname:27017/", tls=True, tlsCAFile="/path/to/ca.pem", tlsCertificateKeyFile="/path/to/client.pem" ) try: client.admin.command("ping") print("Secure connection established") except Exception as e: print(f"Connection failed: {e}") finally: client.close() ``` -------------------------------- ### Asynchronous MongoDB Connection and Query with PyMongo Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Demonstrates how to establish an asynchronous connection to MongoDB using AsyncMongoClient and perform non-blocking database operations, such as querying for a document. This is suitable for applications requiring high concurrency and responsiveness. ```python import asyncio from pymongo import AsyncMongoClient async def main(): uri = "mongodb://localhost:27017/" client = AsyncMongoClient(uri) try: database = client.get_database("sample_mflix") movies = database.get_collection("movies") # Asynchronous query query = {"title": "Back to the Future"} movie = await movies.find_one(query) print(movie) finally: await client.close() asyncio.run(main()) ``` -------------------------------- ### PyMongo: Disable Certificate Validation Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security Illustrates how to disable certificate validation when establishing a TLS connection with PyMongo by setting `tlsAllowInvalidCertificates` to `True`. This is generally not recommended for production environments due to security risks. Examples are provided for both synchronous and asynchronous clients, and for connection string configurations. ```python client = pymongo.MongoClient("mongodb://:@:", tls=True, tlsAllowInvalidCertificates=True) ``` ```python uri = ("mongodb://:@:/?" "tls=true" "&tlsAllowInvalidCertificates=true") client = pymongo.MongoClient(uri) ``` ```python client = pymongo.AsyncMongoClient("mongodb://:@:", tls=True, tlsAllowInvalidCertificates=True) ``` ```python uri = ("mongodb://:@:/?" "tls=true" "&tlsAllowInvalidCertificates=true") client = pymongo.AsyncMongoClient(uri) ``` -------------------------------- ### Configure Connection with Timeouts and Compression in Python Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Illustrates how to configure a PyMongo client connection with specific timeouts (server selection, connection, socket) and compression settings (compressors, zlib level). It also shows using a timeout context for operations. ```python import pymongo from pymongo import MongoClient # Configure connection with timeouts and compression client = MongoClient( "mongodb://hostname:27017/", serverSelectionTimeoutMS=5000, connectTimeoutMS=10000, socketTimeoutMS=20000, maxPoolSize=50, minPoolSize=10, compressors="snappy,zstd,zlib", zlibCompressionLevel=6 ) try: # Use timeout context for operations with pymongo.timeout(5.0): database = client["test_db"] collection = database["test_collection"] result = collection.find_one({"key": "value"}) print(f"Result: {result}") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Estimate Document Count with PyMongo (Python) Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud Shows how to get an estimated count of documents in a collection using PyMongo. This method is faster than `count_documents` as it doesn't perform a query but relies on metadata. Use this when an approximate count is sufficient and performance is a priority. The output is an integer representing the estimated count. ```python count = collection.estimated_document_count() print(count) ``` ```python count = await collection.estimated_document_count() print(count) ``` -------------------------------- ### Configure mod_wsgi for PyMongo Applications Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/integrations These Apache configurations demonstrate how to host PyMongo applications using mod_wsgi. Key directives include `WSGIDaemonProcess` for daemon mode, `WSGIScriptAlias` to map URLs to applications, `WSGIProcessGroup` for process isolation, and `WSGIApplicationGroup %{GLOBAL}` to ensure the application runs in the daemon's main interpreter. This configuration helps avoid potential issues with BSON decoding in sub-interpreters. ```apache WSGIDaemonProcess my_process WSGIScriptAlias /my_app /path/to/app.wsgi WSGIProcessGroup my_process WSGIApplicationGroup %{GLOBAL} ``` ```apache WSGIDaemonProcess my_process WSGIScriptAlias /my_app /path/to/app.wsgi WSGIProcessGroup my_process WSGIDaemonProcess my_other_process WSGIScriptAlias /my_other_app /path/to/other_app.wsgi WSGIProcessGroup my_other_process WSGIApplicationGroup %{GLOBAL} ``` -------------------------------- ### Execute MongoDB Command with Read Preference in Python Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt Shows how to execute a MongoDB command ('hello') with a specific read preference (Secondary) using PyMongo. This allows controlling which replica set member the command is directed to. ```python from pymongo import MongoClient from pymongo.read_preferences import Secondary client = MongoClient("mongodb://localhost:27017/") database = client["sample_mflix"] try: # Execute command with specific read preference result = database.command( "hello", read_preference=Secondary() ) print(f"Command executed on: {result.get('me')}") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### Pretty Print Explanation Results Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/aggregation Uses Python's `pprint` module to format and display the explanation results from MongoDB in a more readable structure. This is useful for analyzing complex execution plans. ```python import pprint ... pprint.pp(result) ``` -------------------------------- ### Delete Single Document in MongoDB with Python Source: https://context7.com/context7/mongodb_languages_python_pymongo-driver_current/llms.txt This Python script uses PyMongo to delete a single document from a MongoDB collection based on a provided filter. In this example, it removes the document named 'Old Product'. The script requires a connection to a MongoDB instance, specifically the 'store' database and its 'products' collection. ```python from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") database = client["store"] collection = database["products"] try: query_filter = {"name": "Old Product"} result = collection.delete_one(query_filter) print(f"Deleted {result.deleted_count} document(s)") except Exception as e: print(f"Error: {e}") finally: client.close() ``` -------------------------------- ### MongoClient Type Annotation Source: https://www.mongodb.com/docs/languages/python/pymongo-driver/current/run-command Demonstrates the correct way to add a type annotation to a MongoClient object to prevent type checker errors. ```python from pymongo import MongoClient client: MongoClient = MongoClient() ```