Azure Cosmos DB is a fully managed NoSQL database service that provides global distribution, automatic scaling, and multiple database APIs. Developers commonly use the Azure portal to create accounts, manage databases, configure containers, and inspect documents. However, performing every operation manually through a graphical interface can become time-consuming, especially when managing multiple environments.
Command-line tools provide a faster and more repeatable way to manage Azure Cosmos DB. They are useful for creating database resources, updating account configurations, executing queries, importing documents, automating deployments, and troubleshooting permissions.
Azure provides two important command-line options for working with Cosmos DB:
Azure CLI: Primarily manages Azure resources, including Cosmos DB accounts, regions, databases, containers, throughput, and other account-level settings.
Azure Cosmos DB Shell: An open-source command-line interface designed for interacting directly with NoSQL databases, documents, queries, and data operations.
Understanding the difference between these tools helps developers select the right approach for each task.
This article explains how to install and configure the tools, manage Cosmos DB resources, work with documents, execute queries, automate operations, and follow security best practices.
Understanding Azure Cosmos DB Command-Line Tools
Azure Cosmos DB management involves two different types of operations.
The first is control-plane management. These operations manage Azure resources through Azure Resource Manager. Examples include creating a database account, adding a region, configuring failover, and changing throughput.
The second is data-plane management. These operations work directly with database contents. Examples include inserting documents, updating records, querying containers, and deleting items.
Azure CLI and Azure Cosmos DB Shell serve different purposes in this architecture.
Azure CLI
Azure CLI is Microsoft's cross-platform command-line tool for managing Azure resources.
It uses the az command followed by resource-specific command groups.
For example:
az cosmosdb list
This command lists Azure Cosmos DB accounts accessible in the selected subscription.
Other common operations include:
Creating and deleting Cosmos DB accounts.
Configuring database regions.
Managing failover priorities.
Creating SQL API databases and containers.
Updating provisioned throughput.
Managing account keys.
Configuring backup settings.
Managing network access and other account properties.
Azure CLI is particularly useful in deployment scripts, CI/CD pipelines, and infrastructure automation.
Azure Cosmos DB Shell
Azure Cosmos DB Shell is an open-source CLI designed specifically for working with Azure Cosmos DB for NoSQL.
It provides a database-oriented command experience with familiar navigation commands such as cd, ls, and pwd.
It also supports:
Connecting to Cosmos DB accounts.
Browsing databases and containers.
Inspecting document structures.
Running SQL queries.
Creating, replacing, patching, and deleting documents.
Importing and exporting JSON and CSV data.
Executing transactional batches.
Running bulk operations.
Inspecting permissions and connection problems.
Automating workflows with scripts.
The shell can run independently from a terminal or through the Azure Cosmos DB extension for Visual Studio Code. It also supports an optional local Model Context Protocol (MCP) server for compatible AI clients.
Comparing Azure CLI and Cosmos DB Shell
Feature | Azure CLI | Cosmos DB Shell |
|---|
Main purpose | Azure resource management | Database operations |
Account creation | Yes | No, uses an existing account |
Region management | Yes | No |
Database and container management | Yes | Yes |
Document operations | Limited resource-management support | Yes |
SQL queries | Not its primary purpose | Yes |
Import and export | Usually through additional tools or scripts | Built-in |
Throughput configuration | Yes | Yes, for supported container operations |
CI/CD automation | Yes | Yes |
MCP integration | Through other integrations | Optional local MCP server |
A practical development environment can use both tools. Azure CLI creates and configures the infrastructure, while Cosmos DB Shell handles database inspection and data operations.
Installing Azure CLI
Azure CLI is available for Windows, macOS, and Linux.
You can install it using the official installation package for your operating system or use Azure Cloud Shell, which provides a preconfigured environment in the Azure portal.
After installation, open a terminal and verify the version:
az version
If an older version is installed, upgrade it:
az upgrade
The Cosmos DB management documentation specifies Azure CLI version 2.22.1 or later for its documented workflows. For newer commands and capabilities, use a current supported Azure CLI release.
Sign In to Azure
Before managing Cosmos DB resources, authenticate with your Azure account.
az login
The command opens a browser-based authentication process. Complete the sign-in and return to the terminal.
If your account has access to multiple subscriptions, list them:
az account list --output table
Select the subscription you want to use:
az account set --subscription "My Azure Subscription"
Verify the active subscription:
az account show --output table
This step is important because Azure CLI commands operate within the currently selected subscription unless you specify another one.
Installing Azure Cosmos DB Shell
Azure Cosmos DB Shell is available through three installation options:
For developers who already use .NET, the global tool is a convenient option. It requires the .NET 10 SDK or later. Self-contained binaries include their runtime and do not require a separate .NET installation.
You can also install the Azure Cosmos DB extension in Visual Studio Code and launch the shell from the editor.
After installation, open a terminal and start the shell:
cosmosdbshell
Check the installed version:
version
To understand the available commands, use:
help
For command-specific options, use:
help connect
The shell is currently focused on the NoSQL API. Developers working with Cassandra, MongoDB, Gremlin, or Table APIs should use the corresponding Azure CLI command groups and API-specific tools.
Connecting to an Azure Cosmos DB Account
Once the shell is installed, connect it to an existing Cosmos DB account.
The preferred approach is Microsoft Entra ID authentication.
connect https://<account-name>.documents.azure.com/ --tenant=<tenant-id>
Replace the account name and tenant ID with your actual values.
The shell uses interactive authentication when the tenant option is provided. It can also use managed identities, account keys, and the default credential chain.
After connecting, inspect the account:
info --format=json
List available databases:
ls
You can also inspect a specific database:
ls --database=MyDatabase
To navigate to a container:
cd /MyDatabase/MyContainer
Check the current database location:
pwd
The pwd command shows the current navigation location. It does not identify the connected account. Use info at the account root to inspect account information.
This distinction is important when managing multiple Cosmos DB accounts from the same terminal session.
Managing Cosmos DB Accounts With Azure CLI
Azure CLI provides commands for creating, listing, inspecting, updating, and deleting Cosmos DB accounts.
List Existing Accounts
To list all Cosmos DB accounts in the active subscription:
az cosmosdb list --output table
To list accounts within a particular resource group:
az cosmosdb list \
--resource-group MyResourceGroup \
--output table
Create a Cosmos DB Account
The following example creates a Cosmos DB account using the NoSQL API.
az cosmosdb create \
--name mycosmosaccount \
--resource-group MyResourceGroup \
--default-consistency-level Session \
--locations regionName="East US" failoverPriority=0 isZoneRedundant=False
The account name must be lowercase and fewer than 44 characters.
The command configures session consistency and the primary region. You can add more regions by providing additional location settings.
Account creation is a long-running operation. Azure CLI normally waits for the operation to complete unless you use an appropriate no-wait option.
Display Account Details
Use the following command to retrieve account information:
az cosmosdb show \
--name mycosmosaccount \
--resource-group MyResourceGroup \
--output json
For a compact output, use a JMESPath query:
az cosmosdb show \
--name mycosmosaccount \
--resource-group MyResourceGroup \
--query "{name:name,location:locations[0].locationName,endpoint:documentEndpoint}" \
--output json
This is useful when scripts need only a few account properties instead of the complete resource definition.
Update Account Settings
You can update supported account properties through the az cosmosdb update command.
For example, enable automatic failover:
az cosmosdb update \
--name mycosmosaccount \
--resource-group MyResourceGroup \
--enable-automatic-failover true
Before changing production account settings, review the impact on availability, consistency, and application behavior.
Creating Databases and Containers
After creating the Cosmos DB account, you can create databases and containers through Azure CLI.
Create a SQL API Database
az cosmosdb sql database create \
--account-name mycosmosaccount \
--resource-group MyResourceGroup \
--name OrdersDatabase
The command creates a database under the specified account.
If you want database-level shared throughput, provide the throughput option:
az cosmosdb sql database create \
--account-name mycosmosaccount \
--resource-group MyResourceGroup \
--name OrdersDatabase \
--throughput 400
Choose shared throughput only when the database and its containers have workload characteristics that make sharing capacity appropriate.
Create a Container
A container stores JSON documents and defines the partition key used to distribute data.
az cosmosdb sql container create \
--account-name mycosmosaccount \
--resource-group MyResourceGroup \
--database-name OrdersDatabase \
--name Orders \
--partition-key-path "/tenantId" \
--throughput 700
This command creates an Orders container with /tenantId as its partition key and 700 RU/s of provisioned throughput.
The partition key should be selected based on application query patterns and expected data distribution. Changing the partition key later generally requires creating a new container and migrating the data.
List Containers
To list containers in a database:
az cosmosdb sql container list \
--account-name mycosmosaccount \
--resource-group MyResourceGroup \
--database-name OrdersDatabase \
--output table
To inspect one container:
az cosmosdb sql container show \
--account-name mycosmosaccount \
--resource-group MyResourceGroup \
--database-name OrdersDatabase \
--name Orders
These commands are useful for deployment verification and environment checks.
Working With Documents Using Cosmos DB Shell
Azure CLI is primarily designed for managing Azure resources. For document operations, Cosmos DB Shell provides a more direct workflow.
Assume the application has an Orders container with /tenantId as its partition key.
A sample document might look like this:
{
"id": "order-1001",
"tenantId": "tenant-25",
"customerId": "customer-101",
"status": "Pending",
"totalAmount": 1250.50
}
Inspect the Document Schema
Before querying an unfamiliar container, inspect a sample of its documents:
schema --database=OrdersDatabase --container=Orders --sample=20
The shell infers field names and types from the sampled documents.
This is useful when working with an existing database where the document structure is not fully documented.
The inferred schema is based on the sample. It is not an enforced database schema and may not represent every document.
Insert a Document
Use mkitem to create a document:
mkitem '{"id":"order-1001","tenantId":"tenant-25","customerId":"customer-101","status":"Pending","totalAmount":1250.50}' --database=OrdersDatabase --container=Orders
The document must include the partition key property and a unique item ID within the relevant logical partition.
Writes require the appropriate permissions and consume request units.
Query Documents
The shell supports Azure Cosmos DB SQL queries.
For example, retrieve orders belonging to a tenant:
query "SELECT * FROM c WHERE c.tenantId = 'tenant-25'" --database=OrdersDatabase --container=Orders --max=20
To retrieve only selected fields:
query "SELECT c.id, c.status, c.totalAmount FROM c WHERE c.tenantId = 'tenant-25'" --database=OrdersDatabase --container=Orders --max=20
The --max option limits the number of returned documents.
You can also inspect the first-page query execution and available index metrics:
query "SELECT c.id FROM c WHERE c.tenantId = 'tenant-25'" --database=OrdersDatabase --container=Orders --explain
The explain operation is a diagnostic probe. It consumes request units and does not measure the complete query execution.
Read a Specific Document
Use print to retrieve an item by its exact ID and complete partition key:
print order-1001 tenant-25 --database=OrdersDatabase --container=Orders
A point read is generally more efficient than running a broad query when both the item ID and partition key are known.
Update a Document
Use patch to change a specific property without replacing the complete document.
patch set order-1001 tenant-25 /status Shipped --database=OrdersDatabase --container=Orders
The set operation updates the property if it exists or creates it if it does not.
The shell also supports operations such as add, replace, remove, and incr.
For production updates, consider using an ETag condition to prevent overwriting a document that another process has modified.
Delete a Document
Deleting data requires additional care.
The shell provides a dry-run option that allows you to review the target before performing a destructive operation.
For example:
rm order-1001 --key=id --partition-key=tenant-25 --database=OrdersDatabase --container=Orders --dry-run
Review the returned ID, partition key, and ETag. Confirm that exactly one intended document is selected.
Only after verifying the result should you repeat the operation without --dry-run, using the returned ETag as a condition where supported.
Do not assume that a delete pattern automatically matches the document ID. The shell's default matching behavior uses the partition key. Use the explicit ID selector and complete partition key for an exact item deletion.
Managing Throughput From the Command Line
Throughput determines how many request units are available to a Cosmos DB database or container.
Azure CLI supports managing provisioned throughput at both levels where the resource configuration allows it.
To inspect container throughput:
az cosmosdb sql container throughput show \
--account-name mycosmosaccount \
--resource-group MyResourceGroup \
--database-name OrdersDatabase \
--name Orders
To update provisioned throughput:
az cosmosdb sql container throughput update \
--account-name mycosmosaccount \
--resource-group MyResourceGroup \
--database-name OrdersDatabase \
--name Orders \
--throughput 1000
You can also migrate between manual and autoscale throughput where supported.
For example, migrate a container to autoscale:
az cosmosdb sql container throughput migrate \
--account-name mycosmosaccount \
--resource-group MyResourceGroup \
--database-name OrdersDatabase \
--name Orders \
--throughput-type autoscale
Check the installed command's help if the parameter syntax differs in your Azure CLI version.
Autoscale is useful for workloads with changing traffic. However, increasing the maximum throughput does not guarantee that every request will avoid throttling. Partition distribution, request patterns, and service limits also matter.
Importing and Exporting Documents
Cosmos DB Shell provides built-in import and export commands for moving data between files and containers.
To export documents:
export orders-backup.json --database=OrdersDatabase --container=Orders --max=1000
The command writes a JSON array to the destination file. You can also export to CSV by using a .csv filename.
For example:
export orders.csv --database=OrdersDatabase --container=Orders --max=1000
To import documents from a JSON file:
import orders-backup.json --database=OrdersDatabase --container=Orders --dry-run
The dry run validates the input format and item IDs without writing to the target database.
After reviewing the validation result, run the import without --dry-run.
Keep in mind that an import dry run does not verify every target-side requirement, such as partition key compatibility, permissions, and conflicts with existing IDs.
For large imports, plan the operation carefully. Monitor RU consumption and use a suitable concurrency strategy rather than sending unrestricted write requests.
Automating Bulk Operations
When working with many documents, executing individual commands manually is inefficient.
Cosmos DB Shell supports bulk operations using JSON arrays, JSON Lines files, and piped input.
For example, create a file named operations.jsonl:
{"op":"create","item":{"id":"bulk-1001","tenantId":"tenant-25","status":"Pending"}}
{"op":"create","item":{"id":"bulk-1002","tenantId":"tenant-26","status":"Pending"}}
{"op":"create","item":{"id":"bulk-1003","tenantId":"tenant-27","status":"Pending"}}
Preview the operation:
bulk run operations.jsonl --database=OrdersDatabase --container=Orders --dry-run
After reviewing the plan, execute it:
bulk run operations.jsonl --database=OrdersDatabase --container=Orders --yes
You can also use a journal to make bulk execution resumable:
bulk run operations.jsonl --database=OrdersDatabase --container=Orders --yes --journal=orders-journal.json
The journal records operation results so successful operations are not blindly repeated when a job resumes.
Bulk operations are not the same as transactional batches. Individual bulk operations can succeed or fail independently. Use a transactional batch when multiple operations must succeed or roll back together within the same logical partition.
Using Azure Cosmos DB Commands in CI/CD Pipelines
Command-line tools are especially useful in automated deployment workflows.
A typical pipeline can use Azure CLI to provision the required infrastructure and Cosmos DB Shell to perform data checks or controlled data operations.
For example, a deployment script can define resource names and create a database:
#!/usr/bin/env bash
set -euo pipefail
RESOURCE_GROUP="MyResourceGroup"
ACCOUNT_NAME="mycosmosaccount"
DATABASE_NAME="OrdersDatabase"
CONTAINER_NAME="Orders"
az account show
az cosmosdb sql database create \
--account-name "$ACCOUNT_NAME" \
--resource-group "$RESOURCE_GROUP" \
--name "$DATABASE_NAME"
az cosmosdb sql container create \
--account-name "$ACCOUNT_NAME" \
--resource-group "$RESOURCE_GROUP" \
--database-name "$DATABASE_NAME" \
--name "$CONTAINER_NAME" \
--partition-key-path "/tenantId" \
--throughput 700
echo "Cosmos DB resource configuration completed."
The script uses set -euo pipefail to stop when a command fails, an undefined variable is used, or a pipeline operation returns an error.
For production pipelines, use workload identity federation or a managed identity where supported. Avoid storing account keys or long-lived credentials directly in pipeline files.
Also, make deployment scripts idempotent where possible. A script should be able to run more than once without accidentally creating duplicate resources or deleting existing data.
For larger infrastructure deployments, Bicep or Terraform can provide a more structured and reviewable approach than a long collection of CLI commands.
Troubleshooting Common Command-Line Problems
Authentication Errors
If az login succeeds but Cosmos DB operations fail, verify that the signed-in identity has the required permissions.
Azure resource management permissions and Cosmos DB data-plane permissions are different. Having permission to view an account does not automatically mean you can read or modify documents.
Use the shell's identity and permission diagnostics:
whoami --format=json
can-i query --database=OrdersDatabase --container=Orders
The can-i command reports an access probe result. It does not replace a full RBAC review.
Account Connection Failures
If the shell cannot connect, check the account endpoint, identity, network access, and firewall configuration.
Cosmos DB Shell does not bypass account firewall rules or private-network restrictions.
You can run diagnostics using:
doctor --no-update-check --format=json
Resource Not Found
If a database or container cannot be found, verify the account, database name, container name, and active subscription.
With Azure CLI, check the account details:
az cosmosdb show \
--name mycosmosaccount \
--resource-group MyResourceGroup
With Cosmos DB Shell, inspect the account and available resources:
info --format=json
ls
Request Unit Throttling
If queries or writes receive HTTP 429 responses, the operation may be consuming more throughput than is available.
Review query metrics, partition key usage, and request patterns. Reduce unnecessary concurrency and use a suitable throughput configuration.
Unexpected Document Deletion
If a delete operation selects more documents than expected, stop before executing it.
Use --dry-run, specify the complete partition key, and verify the returned item ID and ETag. Never remove the dry-run option until the target has been reviewed.
Security Best Practices
Command-line tools can make database administration faster, but they also make it easy to perform destructive operations.
Follow these practices when managing production Cosmos DB accounts:
Prefer Microsoft Entra ID authentication over account keys.
Use managed identities or workload identity federation in automated environments.
Assign only the permissions required for each operation.
Keep development, staging, and production account configurations separate.
Verify the active Azure subscription before running resource-changing commands.
Use explicit database and container targets in scripts.
Review dry-run results before bulk updates or deletions.
Use ETags for conditional document modifications.
Keep credentials out of shell scripts and source control.
Monitor request unit consumption during queries and bulk operations.
Maintain backups and test restoration procedures.
Review command history and diagnostic output before sharing it with others.
Be particularly careful when using commands such as az cosmosdb delete, rmdb, rmcon, and rm. These operations can permanently remove important resources or data.
Advantages and Disadvantages of Command-Line Management
Advantages
Faster resource management than performing every operation manually in the portal.
Repeatable infrastructure setup through scripts.
Easier integration with CI/CD pipelines.
Direct access to database documents and queries through Cosmos DB Shell.
Support for bulk import and export workflows.
Better automation for development and testing environments.
Useful diagnostics for connection and permission problems.
Reduced manual effort when managing multiple environments.
Disadvantages
Requires familiarity with command syntax and authentication.
Incorrect commands can modify or delete production resources.
Azure CLI and Cosmos DB Shell have different responsibilities and learning curves.
Some commands require additional extensions or newer tool versions.
Data-plane operations can consume significant request units.
Network restrictions can prevent command-line access.
Scripts require proper error handling and credential management.
Conclusion
Managing Azure Cosmos DB from the command line gives developers and administrators more control over database resources and everyday data operations. Azure CLI provides commands for creating accounts, configuring regions, managing databases and containers, and updating throughput. Azure Cosmos DB Shell adds a database-focused experience for querying, inspecting, importing, exporting, and modifying documents.
Using both tools together creates a practical workflow. Azure CLI handles infrastructure and account management, while Cosmos DB Shell handles direct database interaction. Both can be integrated into scripts and CI/CD pipelines to reduce repetitive manual work.
For production environments, command-line automation should always include authentication controls, explicit resource targeting, error handling, and safeguards for destructive operations. With these practices in place, developers can manage Cosmos DB environments more consistently and efficiently.
Join the conversation! Your thoughts help the community grow.