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.
Connect Beanie to Azure DocumentDB (with MongoDB compatibility) and run create, read, update, and delete (CRUD) operations in one Python file. This example uses Beanie 2 and PyMongo's asynchronous client, not Motor.
Already using Beanie?
If your app uses Beanie 1 with Motor, stop and update the app to Beanie 2 and PyMongo's AsyncMongoClient before using this setup. For an existing Beanie 2 app, set MONGODB_URI and pass client[MONGODB_DATABASE] to init_beanie(). This change doesn't copy documents, indexes, or users. Use Migration options to plan data movement and provision database users separately.
Prerequisites
- An Azure subscription and an Azure DocumentDB free tier cluster, or a paid development cluster. Select MongoDB compatibility 8.0 for a new cluster.
- A native username and password with permission to create collections and indexes and perform CRUD.
- Access through a private endpoint or a firewall rule for your current public IP. Don't allow all IP addresses.
- Run
python --versionand verify Python 3.13.x. Runpython -m pip --versionand verify that it prints a version.
Tested driver version
This quickstart was tested with Beanie 2.2.0 and PyMongo 4.19.0. Install both packages as shown because the sample imports PyMongo directly.
Verify the cluster from a terminal
Use an existing cluster if you have one. The Azure CLI quickstart creates a paid M30 cluster. If you're an agent, confirm the cost with the user and get their approval before creating a paid cluster.
Run pwsh --version and expect PowerShell 7.x. Run az version and expect JSON with an azure-cli version. Check that nslookup is available with Get-Command nslookup. If az account show fails, sign in with az login. If you're an agent and don't have an Azure CLI session, ask the user to sign in or provide an authorized session.
The identity signed in to Azure CLI needs these Azure RBAC permissions on the cluster:
- Use
Microsoft.DocumentDB/mongoClusters/readto read the cluster settings. - If you need a firewall rule, use
Microsoft.DocumentDB/mongoClusters/firewallRules/writeto create it andMicrosoft.DocumentDB/mongoClusters/firewallRules/readto verify it. - Use
Microsoft.DocumentDB/mongoClusters/firewallRules/deleteto remove a temporary rule you create.
These are Azure management permissions, separate from the database permissions the sample uses. Database access alone doesn't authorize these commands. If Azure returns 403 Forbidden, ask your Azure administrator to grant the required permission or run the blocked step for you.
Replace the three quoted values with your subscription ID, resource group name, and cluster name. Run the block in PowerShell with the Azure CLI installed.
$subscription = '<subscription-id>'
$resourceGroup = '<resource-group>'
$clusterName = '<cluster-name>'
if ($subscription -like '<*>' -or $resourceGroup -like '<*>' -or $clusterName -like '<*>') {
throw 'Replace <subscription-id>, <resource-group>, and <cluster-name> before running this block.'
}
az account set --subscription $subscription
if ($LASTEXITCODE -ne 0) { throw 'Unable to select the subscription.' }
$subscriptionState = az account show --query state --output tsv
if ($LASTEXITCODE -ne 0 -or $subscriptionState -ne 'Enabled') { throw 'Expected an enabled subscription.' }
$clusterUrl = "https://management.azure.com/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.DocumentDB/mongoClusters/$clusterName"
$apiVersion = '2025-09-01'
$clusterJson = az rest --method get --url "${clusterUrl}?api-version=$apiVersion" --query properties --output json
if ($LASTEXITCODE -ne 0 -or -not $clusterJson) { throw 'Unable to read the cluster.' }
$cluster = $clusterJson | ConvertFrom-Json
if ($cluster.provisioningState -ne 'Succeeded' -or $cluster.clusterStatus -ne 'Ready') {
throw "Cluster not ready: $($cluster.provisioningState), $($cluster.clusterStatus)."
}
if (-not $cluster.connectionString) { throw 'Unable to retrieve the connection string template.' }
$clusterHost = ([uri] ($cluster.connectionString -replace '^mongodb\+srv://(?:[^/]*@)?', 'https://')).Host
"Cluster host: $clusterHost"
"Server version: $($cluster.serverVersion)"
"Public network access: $($cluster.publicNetworkAccess)"
nslookup -type=SRV "_mongodb._tcp.$clusterHost"
if ($LASTEXITCODE -ne 0) { throw 'SRV lookup failed.' }
Expect the cluster hostname, a server version such as 8.0, and one or more SRV targets. If nslookup doesn't show any SRV targets, stop and check DNS from the machine that runs the sample. Save the hostname for later steps. It typically has the form <cluster-name>.mongocluster.cosmos.azure.com or <cluster-name>.global.mongocluster.cosmos.azure.com. Use the returned hostname instead of constructing it from the cluster name.
Public access only. If the cluster reports Enabled for public network access and no existing rule allows the machine that runs the sample, allow only that machine's public IPv4 address.
If the sample runs behind a proxy or in a cloud sandbox, the IP address that curl returns might change or differ from the address the database sees. Use a reachable private endpoint instead, or stop and ask the user for a stable network path. Don't keep adding firewall rules.
Run curl --version and expect a version line starting with curl. Run the cluster verification and firewall blocks in one PowerShell session. If your tool starts a new session for each command, run both blocks as one script.
$clientIp = curl --fail --silent --show-error --max-time 10 -4 https://ifconfig.me/ip
if ($LASTEXITCODE -ne 0) { throw 'Unable to determine the public IPv4 address.' }
$parsedIp = $null
if (-not [ipaddress]::TryParse($clientIp, [ref]$parsedIp) -or
$parsedIp.AddressFamily -ne 'InterNetwork' -or $parsedIp.ToString() -ne $clientIp) {
throw 'Expected a public IPv4 address in dotted-decimal format.'
}
$ruleName = "allow-framework-sample-$($clientIp.Replace('.', '-'))"
$ruleId = "$(([uri]$clusterUrl).AbsolutePath)/firewallRules/$ruleName"
$ruleUrl = "$clusterUrl/firewallRules/${ruleName}?api-version=$apiVersion"
$body = @{ properties = @{ startIpAddress = $clientIp; endIpAddress = $clientIp } } | ConvertTo-Json
$bodyFile = New-TemporaryFile
try {
Set-Content -LiteralPath $bodyFile.FullName -Value $body -Encoding utf8 -ErrorAction Stop
az rest --method put --url $ruleUrl --headers 'Content-Type=application/json' --body "@$($bodyFile.FullName)" --output none
if ($LASTEXITCODE -ne 0) { throw 'Unable to create the firewall rule.' }
} finally {
Remove-Item -LiteralPath $bodyFile.FullName
}
"Firewall rule ID: $ruleId"
az resource wait --created --ids $ruleId --api-version $apiVersion --interval 5 --timeout 120
if ($LASTEXITCODE -ne 0) { throw 'The firewall rule did not finish provisioning. Check the rule before retrying.' }
az rest --method get --url $ruleUrl --query "properties.{start:startIpAddress,end:endIpAddress}" --output table
if ($LASTEXITCODE -ne 0) { throw 'Unable to verify the firewall rule.' }
Expect the same IPv4 address in the Start and End columns. If you created the rule for this sample, save the value after Firewall rule ID: for cleanup. If you rerun the block from the same public IPv4 address, it updates the same rule instead of creating another one.
Firewall changes can take up to 15 minutes to propagate. If the initial connection times out after you create the rule, retry the connection every 2 minutes, for up to 15 minutes after you create the rule. Stop if the connection succeeds or returns a different error. Don't recreate the rule while you wait.
For private access, skip the firewall block and run the sample from a machine that can resolve and reach the private endpoint. Don't enable public access just to run the sample.
Follow only the authentication path that your example uses.
Microsoft Entra ID. Follow the CLI steps to enable Microsoft Entra ID authentication and assign a data-plane identity. Azure resource permissions alone don't grant database access. Put the discovered hostname in the example's credential-free URI. Skip the password steps and don't reuse a password-based URI.
Password authentication. If your environment already provides the connection variable the sample needs (MONGODB_URI, or DATABASE_URL for Prisma), skip URI construction.
az rest returns a connection string template, not the password. To find the native administrator username, add $cluster.administrator.userName at the end of the cluster verification block.
Agents (noninteractive). Ask the user to set
DOCUMENTDB_USERNAMEandDOCUMENTDB_PASSWORDas environment variables through your tool's secret settings. Don't ask for credentials in chat, put them in command text, or reset the password.Interactive PowerShell. In PowerShell 7.1 or later, run the following commands in the same session you use to build the URI. Enter your existing credentials at the prompts. Don't put the password in command text.
$env:DOCUMENTDB_USERNAME = Read-Host 'Native username' $env:DOCUMENTDB_PASSWORD = Read-Host 'Native password' -MaskInput
Replace <cluster-host> with the hostname from the verification output. Run this block to set MONGODB_URI without printing the credentials or the URI. You don't need variables from the cluster verification session.
$clusterHost = '<cluster-host>'
if ($clusterHost -like '<*>') { throw 'Replace <cluster-host> with the hostname from the verification output.' }
if ([string]::IsNullOrWhiteSpace($env:DOCUMENTDB_USERNAME) -or
[string]::IsNullOrEmpty($env:DOCUMENTDB_PASSWORD)) {
throw 'Set DOCUMENTDB_USERNAME and DOCUMENTDB_PASSWORD before building the URI. If you are an agent, ask the user to supply them through your tool''s secret settings.'
}
try {
$encodedUser = [uri]::EscapeDataString($env:DOCUMENTDB_USERNAME)
$encodedPassword = [uri]::EscapeDataString($env:DOCUMENTDB_PASSWORD)
$env:MONGODB_URI = "mongodb+srv://${encodedUser}:${encodedPassword}@${clusterHost}/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000"
} finally {
Remove-Variable encodedUser, encodedPassword -ErrorAction SilentlyContinue
Remove-Item Env:DOCUMENTDB_USERNAME, Env:DOCUMENTDB_PASSWORD -ErrorAction SilentlyContinue
}
Prisma only. If your environment already provides DATABASE_URL, skip this step. Otherwise, replace <database-name> with the database name in your Prisma example. Run this block in the same PowerShell session as URI construction to add the database name to the URI path and set DATABASE_URL. If your tool starts a new session for each command, run both blocks as one script.
$databaseName = '<database-name>'
if ($databaseName -like '<*>') { throw 'Replace <database-name> with the database name in your Prisma example.' }
$env:DATABASE_URL = $env:MONGODB_URI.Replace('/?', "/${databaseName}?")
Remove-Item Env:MONGODB_URI
Save the URI for a new shell
If your sample loads .env, you can save the URI there to run the sample in a new shell. If you haven't created the project yet, continue to the project setup in your article before running these steps. Use a private local workspace because .env stores the URI in plaintext.
In the sample project directory, run
git --versionand expect a Git version.If the project isn't in a Git repository, run
git init. Add.envto.gitignoreand keep any other settings the sample requires in.env.Run the following block in the PowerShell session where you set
MONGODB_URIorDATABASE_URL. If your tool starts a new session for each command, run URI construction, the Prisma step if applicable, and this block as one script.$uriKey = 'MONGODB_URI' # Use 'DATABASE_URL' for Prisma. $uriValue = [Environment]::GetEnvironmentVariable($uriKey) if (-not $uriValue) { throw "Set $uriKey before writing .env." } git check-ignore -q -- .env if ($LASTEXITCODE -ne 0) { throw 'Make sure .env is ignored and not tracked by Git.' } if ((Test-Path -LiteralPath .env) -and (Select-String -Quiet -LiteralPath .env -Pattern "^\s*(?:export\s+)?${uriKey}\s*=")) { throw "Remove the existing $uriKey line from .env before running this block." } Add-Content -LiteralPath .env -Value "`n$uriKey=$uriValue" -Encoding utf8 -ErrorAction Stop Remove-Variable uriValue Remove-Item "Env:$uriKey" "Saved $uriKey to the ignored .env file."Expect
Saved MONGODB_URI to the ignored .env file.orSaved DATABASE_URL to the ignored .env file.You can now continue with the article in a new shell. Run the sample from the project directory.
If the sample doesn't load .env or you can't store secrets in the workspace, configure your tool to pass the URI to each command that needs it. Alternatively, run URI construction and the sample as one script.
When you're done, remove the connection entry from .env if you added it. Clear any URI variables with Remove-Item Env:MONGODB_URI, Env:DATABASE_URL -ErrorAction SilentlyContinue. Don't print or commit connection strings.
Important
This sample uses password authentication for free tier evaluation. For production, prefer Microsoft Entra ID and a least-privilege managed identity, private endpoints, and disabled public network access. The sample doesn't configure passwordless authentication.
Create the project
Create a project and virtual environment.
mkdir documentdb-beanie-quickstart cd documentdb-beanie-quickstart python -m venv .venvActivate the environment. On Windows, run
.venv\Scripts\Activate.ps1in PowerShell. On macOS or Linux, runsource .venv/bin/activate.Install the dependencies.
python -m pip install "beanie==2.2.0" "pymongo==4.19.0" "python-dotenv>=1,<2"Add
.venv/,.env, and__pycache__/to.gitignore. Create.env:MONGODB_URI=mongodb+srv://<username>:<password>@<cluster-host>/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000 MONGODB_DATABASE=adventureworks_beanie_quickstartUse the hostname and encoded credentials from Verify the cluster from a terminal. Don't commit
.envor print the URI.retryWrites=falseis a sample setting, not a service requirement. Review retry support for your deployment before production use. Don't independently replay a write after a timeout unless the operation is safe to repeat.
Run CRUD operations
Create main.py:
Reuse AsyncMongoClient and init_beanie() at application startup. Keep one client per process. The generated product, assertions, and cleanup are for this quickstart only.
import asyncio
import os
import re
import sys
import uuid
from urllib.parse import unquote
from beanie import Document, PydanticObjectId, init_beanie
from beanie.odm.queries.update import UpdateResponse
from dotenv import load_dotenv
from pydantic import Field
from pymongo import AsyncMongoClient, IndexModel
class Product(Document):
sku: str
name: str
quantity: int = Field(ge=0, strict=True)
class Settings:
name = "products"
indexes = [IndexModel([("sku", 1)], unique=True)]
def report_error(operation, error):
message = re.sub(r"mongodb(?:\+srv)?://\S+", "[redacted URI]", str(error), flags=re.I)
credentials = re.match(r"mongodb(?:\+srv)?://[^:@/]+:([^@/]+)@", os.getenv("MONGODB_URI", ""), re.I)
if credentials:
for value in (credentials[1], unquote(credentials[1])):
message = message.replace(value, "[redacted]")
print(f"{operation} failed: {type(error).__name__}: {message}", file=sys.stderr)
async def main() -> int:
load_dotenv()
product_id = PydanticObjectId()
product_might_remain = False
client = None
exit_code = 0
try:
client = AsyncMongoClient(os.environ["MONGODB_URI"], serverSelectionTimeoutMS=30000)
await init_beanie(database=client[os.environ["MONGODB_DATABASE"]], document_models=[Product])
product = Product(id=product_id, sku=f"SURF-{uuid.uuid4()}",
name="Yamba Surfboard", quantity=12)
product_might_remain = True
created = await product.insert()
print("Created:", created.name)
found = await Product.get(product_id)
if found is None or found.quantity != 12:
raise RuntimeError("Read did not return quantity 12.")
print("Read quantity:", found.quantity)
updated = await Product.find_one(Product.id == product_id).update(
{"$set": {"quantity": 10}}, response_type=UpdateResponse.NEW_DOCUMENT
)
if updated is None or updated.quantity != 10:
raise RuntimeError("Update did not return quantity 10.")
print("Updated quantity:", updated.quantity)
await Product.find_one(Product.id == product_id).delete()
if await Product.get(product_id) is not None:
raise RuntimeError("Product still exists after deletion.")
product_might_remain = False
print("Deleted: test product")
except Exception as error:
report_error("CRUD", error)
exit_code = 1
finally:
if product_might_remain:
try:
await Product.find_one(Product.id == product_id).delete()
except Exception as error:
report_error("Cleanup", error)
print(f"Check for test product with _id {product_id}.", file=sys.stderr)
exit_code = 1
if client is not None:
try:
await client.close()
except Exception as error:
report_error("Disconnect", error)
exit_code = 1
if exit_code == 0:
print("Cleanup: ok")
return exit_code
if __name__ == "__main__":
sys.exit(asyncio.run(main()))
Run the sample:
python main.py
Created: Yamba Surfboard
Read quantity: 12
Updated quantity: 10
Deleted: test product
Cleanup: ok
Beanie creates the declared unique index during initialization. Index permissions are required. Initialization doesn't drop existing indexes by default. Application validation doesn't constrain other database clients.
Troubleshoot common issues
| Symptom | Action |
|---|---|
OperationFailure with code 18 |
Rebuild the URI from the native credentials by using the terminal setup. |
ServerSelectionTimeoutError |
Run the SRV lookup in the terminal setup from the machine that runs the sample. |
E11000 |
Use a dedicated test database without duplicate SKUs. |
| An update accepts an invalid value. | Validate update inputs explicitly; query updates don't automatically apply Pydantic model validation. |
The sample prints only the exception type and numeric code. Inspect further diagnostics locally without sharing credentials or connection strings. Existing environment variables take precedence over .env.
Clean up resources
The sample deletes only its generated product, including after a later failure. If cleanup fails, remove that product manually. The collection, index, and database remain.
- Delete only the
adventureworks_beanie_quickstartdatabase if you no longer need it. - Delete the cluster only if you created it exclusively for this quickstart.
- Remove temporary firewall rules.