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.
In this quickstart, you deploy a basic Azure Cosmos DB for MongoDB application using Python. Azure Cosmos DB for MongoDB vCore is a schemaless data store allowing applications to store unstructured documents in the cloud with MongoDB libraries. You learn how to create documents and perform basic tasks within your Azure Cosmos DB resource using Python.
Library source code | Package (PyPI) | Azure Developer CLI
Azure Developer CLI
Docker Desktop
An Azure subscription
- If you don't have an Azure subscription, create a Trial before you begin.
- Python 3.12
Use the Azure Developer CLI (azd
) to create an Azure Cosmos DB for MongoDB vCore cluster and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.
Open a terminal in an empty directory.
If you're not already authenticated, authenticate to the Azure Developer CLI using
azd auth login
. Follow the steps specified by the tool to authenticate to the CLI using your preferred Azure credentials.azd auth login
Use
azd init
to initialize the project.azd init --template cosmos-db-mongodb-vcore-python-quickstart
During initialization, configure a unique environment name.
Deploy the cluster using
azd up
. The Bicep templates also deploy a sample web application.azd up
During the provisioning process, select your subscription, desired location, and target resource group. Wait for the provisioning process to complete. The process can take approximately ten minutes.
Once the provisioning of your Azure resources is done, a URL to the running web application is included in the output.
Deploying services (azd deploy) (✓) Done: Deploying service web - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io> SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.
The client library is available through PyPi, as the pymongo
package.
Open a terminal and navigate to the
/src
folder.cd ./src
If not already installed, install the
pymongo
package usingpip install
.pip install pymongo
If not already installed, install the
azure.identity
package usingpip install
.pip install azure.identity
Open and review the src/requirements.txt file to validate that both package entries exist.
Import the following namespaces into your application code:
Package | Source | |
---|---|---|
DefaultAzureCredential |
azure.identity |
Azure SDK for Python |
MongoClient |
pymongo |
Official MongoDB driver for Python |
OIDCCallback |
pymongo |
Official MongoDB driver for Python |
OIDCCallbackContext |
pymongo |
Official MongoDB driver for Python |
OIDCCallbackResult |
pymongo |
Official MongoDB driver for Python |
from azure.identity import DefaultAzureCredential
from pymongo import MongoClient
from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResult
Name | Description |
---|---|
MongoClient | Type used to connect to MongoDB. |
Database |
Represents a database in the cluster. |
Collection |
Represents a collection within a database in the cluster. |
- Authenticate the client
- Get a database
- Get a collection
- Create a document
- Get a document
- Query documents
The sample code in the template uses a database named cosmicworks
and collection named products
. The products
collection contains details such as name, category, quantity, and a unique identifier for each product. The collection uses the /category
property as a shard key.
While Microsoft Entra authentication for Azure Cosmos DB for MongoDB vCore can use well known TokenCredential
types, you must implement a custom token handler. This sample implementation can be used to create a MongoClient
with support for standard Microsoft Entra authentication of many identity types.
First, define a class named
AzureIdentityTokenCallback
that defines afetch
function taking in theOIDCCallbackContext
parameter and returning aOIDCCallbackResult
.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.chinacloudapi.cn/.default").token return OIDCCallbackResult(access_token=token)
Use your custom handler class passing in a new instance of the
DefaultAzureCredential
typecredential = DefaultAzureCredential() authProperties = {"OIDC_CALLBACK": AzureIdentityTokenCallback(credential)}
Build an instance of
MongoClient
using your cluster name, and the known best practice configuration options for Azure Cosmos DB for MongoDB vCore. Also, configure your custom authentication mechanism.clusterName = "<azure-cosmos-db-mongodb-vcore-cluster-name>" client = MongoClient( f"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/", connectTimeoutMS=120000, tls=True, retryWrites=True, authMechanism="MONGODB-OIDC", authMechanismProperties=authProperties )
This sample creates an instance of the Database
type using the get_database
function of the MongoClient
type.
database = client.get_database("<database-name>")
This sample creates an instance of the Collection
type using the get_collection
function of the Database
type.
collection = database.get_collection("<collection-name>")
Create a document in the collection using collection.update_one
. This method "upserts" the item effectively replacing the item if it already exists.
new_document = {
"_id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
"category": "gear-surf-surfboards",
"name": "Yamba Surfboard",
"quantity": 12,
"sale": False,
}
filter = {
"_id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
"category": "gear-surf-surfboards"
}
payload = {
"$set": new_document
}
result = collection.update_one(filter, payload, upsert=True);
Perform a point read operation by using both the unique identifier (id
) and shard key fields. Use collection.find_one
to efficiently retrieve the specific item.
filter = {
"_id": "bbbbbbbb-1111-2222-3333-cccccccccccc",
"category": "gear-surf-surfboards"
}
existing_document = collection.find_one(filter)
Perform a query over multiple items in a container using collection.find
. This query finds all items within a specified category (shard key).
filter = {
"category": "gear-surf-surfboards"
}
matched_documents = collection.find(filter)
for document in matched_documents:
# Do something with each item
Delete a document by sending a filter for the unique identifier of the document. Use delete_one
to remove the document from the collection.
filter = {
'_id': id
}
result = collection.delete_one(filter)
Use the Visual Studio Code extension for Azure Cosmos DB to explore your MongoDB vCore data. You can perform core database operations including, but not limited to:
- Performing queries using a scrapbook or the query editor
- Modifying, updating, creating, and deleting documents
- Importing bulk data from other sources
- Managing databases and collections
For more information, see How-to use Visual Studio Code extension to explore Azure Cosmos DB for MongoDB vCore data.
When you no longer need the sample application or resources, remove the corresponding deployment and all resources.
azd down --force