Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This guide walks you through building a Python console application to connect to an Azure DocumentDB cluster. You configure your development environment, authenticate using the azure.identity package from the Azure SDK for Python, and perform operations such as creating, querying, and updating documents.
Prerequisites
An Azure subscription
- If you don't have an Azure subscription, create a free account
An existing Azure DocumentDB cluster
- If you don't have a cluster, create a new cluster
Use the Bash environment in Azure Cloud Shell. For more information, see Get started with Azure Cloud Shell.
If you prefer to run CLI reference commands locally, install the Azure CLI. If you're running on Windows or macOS, consider running Azure CLI in a Docker container. For more information, see How to run the Azure CLI in a Docker container.
If you're using a local installation, sign in to the Azure CLI by using the az login command. To finish the authentication process, follow the steps displayed in your terminal. For other sign-in options, see Authenticate to Azure using Azure CLI.
When you're prompted, install the Azure CLI extension on first use. For more information about extensions, see Use and manage extensions with the Azure CLI.
Run az version to find the version and dependent libraries that are installed. To upgrade to the latest version, run az upgrade.
Microsoft Entra authentication configured for the cluster with your identity granted
rootrole.- To enable Microsoft Entra authentication, review the configuration guide.
Latest version of Python.
Configure your console application
Next, create a new console application project and import the necessary libraries to authenticate to your cluster.
Create a new directory for your project and set up a virtual environment.
mkdir mongodb-app cd mongodb-app python -m venv .venvActivate the virtual environment.
# On Windows .venv\Scripts\activate # On macOS/Linux source .venv/bin/activateCreate a new Python file for your application.
touch app.pyInstall the
azure.identitylibrary for Azure authentication.pip install azure.identityInstall the
pymongodriver for Python.pip install pymongo
Connect to the cluster
Now, use the Azure.Identity library to get a TokenCredential to use to connect to your cluster. The official MongoDB driver has a special interface that must be implemented to obtain tokens from Microsoft Entra for use when connecting to the cluster.
Import the necessary modules at the top of your Python file.
from azure.identity import DefaultAzureCredential from pymongo import MongoClient from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResultCreate a custom class that implements the MongoDB OpenID Connect (OIDC) callback interface.
class AzureIdentityTokenCallback(OIDCCallback): def __init__(self, credential): self.credential = credential def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: token = self.credential.get_token( "https://ossrdbms-aad.database.windows.net/.default").token return OIDCCallbackResult(access_token=token)Set your cluster name variable.
clusterName = "<azure-documentdb-cluster-name>"Create an instance of DefaultAzureCredential and set up the authentication properties.
credential = DefaultAzureCredential() authProperties = {"OIDC_CALLBACK": AzureIdentityTokenCallback(credential)}Create a MongoDB client configured with Microsoft Entra authentication.
client = MongoClient( f"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/", connectTimeoutMS=120000, tls=True, retryWrites=True, authMechanism="MONGODB-OIDC", authMechanismProperties=authProperties ) print("Client created")
Perform common operations
Finally, use the official library to perform common tasks with databases, collections, and documents. Here, you use the same classes and methods you would use to interact with MongoDB or DocumentDB to manage your collections and items.
Get a reference to your database.
database = client.get_database("<database-name>") print("Database pointer created")Get a reference to your collection.
collection = database.get_collection("<container-name>") print("Collection pointer created")Create a document and upsert it into the collection with
collection.update_one.new_document = { "_id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", "category": "gear-surf-surfboards", "name": "Yamba Surfboard", "quantity": 12, "price": 850.00, "clearance": False, } filter = { "_id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", } payload = { "$set": new_document } result = collection.update_one(filter, payload, upsert=True)Use
collection.find_oneto retrieve a specific document from the collection.filter = { "_id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", "category": "gear-surf-surfboards" } existing_document = collection.find_one(filter) print(f"Read document _id:\t{existing_document['_id']}")Query for multiple documents with
collection.findthat matches a filter.filter = { "category": "gear-surf-surfboards" } matched_documents = collection.find(filter) for document in matched_documents: print(f"Found document:\t{document}")