Azure Cosmos DB Shell command reference

Use this reference to discover commands and common workflows. Run help <command> in your installed shell for its exact arguments and options. The examples in this article run inside Azure Cosmos DB Shell, unless a block explicitly starts with cosmosdbshell.

Examples use the sample database ShellDemo, container Items, and partition key /tenantId. Replace resource names with your intended targets. Confirm the account with info at the account root before reading or changing data.

Connection and navigation

Command Purpose
connect <endpoint-or-connection-string> Connect by using Microsoft Entra ID, managed identity, account keys, or the default credential chain.
disconnect Disconnect the current account.
ls List databases, containers, or items at the selected scope.
cd <path> Select a database or container. Use cd to return to the account root and cd .. to move up.
pwd Show the current Azure Cosmos DB location.
info Inspect account, database, or container configuration and usage at the selected scope.
connect https://<account-name>.documents.azure.com/ --tenant=<tenant-id>
info --format=json
ls
cd /ShellDemo/Items
pwd
info --database=ShellDemo --container=Items

pwd identifies navigation, not the connected account. At the account root, info --format=json includes accountId and uri. At other scopes, info describes the database or container instead.

Commands that support --database (--db) and --container (--con) can target resources independently of navigation. Use these options in scripts and MCP calls rather than relying on a previous cd.

ls defaults to 100 items when listing a container. Set --max to a positive bound. info --partitions and info --detailed query data and consume request units (RUs); detailed distribution analysis can scan the container.

Connection options

Option Purpose
--tenant Use interactive Microsoft Entra authentication for this tenant.
--hint Prefill the username for interactive sign-in.
--managed-identity Select a user-assigned managed identity by client ID.
--mode Select direct or gateway connectivity.
--subscription, --resource-group Supply Azure Resource Manager context for account-management operations.

An endpoint without an explicit credential option uses the default credential chain. For a local emulator, use its localhost endpoint. Quote connection strings because semicolons otherwise separate shell commands. Connection strings can be retained in replayable shell history; prefer Microsoft Entra ID.

Diagnostics and schema discovery

Command Purpose
doctor Run bounded, read-only environment and connection diagnostics without changing shell state.
doctor who Add known credential and scope information to the diagnostic report.
whoami Inspect the credential type and available Microsoft Entra identity information.
can-i <action> Probe read, query, write, or manage access without changing data.
schema Infer field names and types from a bounded sample, with partition-key and indexing metadata.
doctor --no-update-check --format=json
doctor --database=ShellDemo --container=Items --query
whoami --format=json
can-i query --database=ShellDemo --container=Items
schema --database=ShellDemo --container=Items --sample=20
schema --database=ShellDemo --container=Items --fields-only

doctor works while disconnected. By default, its update check performs a bounded public GitHub release lookup; --no-update-check disables that lookup, not other requested network checks. --query runs a small query probe and consumes RUs. --arm explicitly requests an Azure Resource Manager check. Results distinguish passed, warning, failed, and skipped checks; a skipped check isn't evidence of success.

can-i reports allow, deny, or indeterminate, not a list of role assignments. The write probe is a heuristic based on delete access, not proof of every write permission. Management access can't be established by this data-plane probe and returns indeterminate.

schema --sample accepts 1-100 documents and defaults to 20. --fields-only (alias --short) omits the container metadata read. Inferred fields describe the sample, not a complete schema or an enforced schema.

Query and point-read commands

query

Execute an Azure Cosmos DB query against a container:

query "SELECT TOP 10 c.id FROM c" --database=ShellDemo --container=Items --max=10
query "SELECT VALUE COUNT(1) FROM c" --database=ShellDemo --container=Items --max=1
Option Purpose
--max, -m Bound returned items. Interactive queries have no default item limit.
--format, -f Select json, table, or csv result presentation.
--metrics, -mx Request query metrics for display or a file.
--explain Inspect first-page execution and index metrics instead of returning documents.
--bucket Select a throughput bucket for this query.
--database, --container Set the query target explicitly.
query "SELECT c.id FROM c WHERE c.tenantId = 'demo'" --database=ShellDemo --container=Items --explain

This example's tenantId property belongs to the sample model in Get started. Inspect your own container with schema before using its properties.

--explain executes a first-page probe, consumes RUs, and doesn't measure the complete query. Missing index metrics produce an unknown assessment rather than proof of a scan. --max doesn't control the explain probe.

Through MCP, queries return bounded pages with continuationToken. Pass a non-null token unchanged as the tool's continuation argument with the same query and options. continuation isn't an interactive shell option. A null token with resultIncomplete: true means truncation that can't be resumed; narrow the query or increase the requested bound.

print

Point-read an item by its exact ID and complete partition key:

print sample-1 demo --database=ShellDemo --container=Items

Partition-key values preserve JSON types:

Value Meaning
680 A numeric key.
'"680"' A string key containing the digits 680.
true or null A Boolean or null key.
'{}' An undefined partition-key value, distinct from null.
'["tenant-1",680]' A complete hierarchical key, in configured path order.

print doesn't fall back to a query if the item isn't found. Older versions treated numeric-looking keys as strings; use explicit JSON-string quoting when needed.

Create and change items

Command Purpose
mkitem <json> Create an item or array of items; also accepts piped JSON.
create item <json> Create items through the generic creation command.
replace <json> Replace an existing document with the supplied document.
patch <operation> <id> <pk> <path> [value] Change a field without replacing the complete document.
rm <pattern> Delete matching items, or preview matches with --dry-run.

Writes require permission on the intended account and container and consume RUs. mkitem --force (alias --upsert) can replace existing items. A replacement must contain the complete intended document, not just the fields you want to change.

patch

Supported operations are set, add, replace, remove, and incr (alias increment). Values use JSON typing.

patch set sample-1 demo /status reviewed --database=ShellDemo --container=Items

set can create a field; replace requires it to exist. remove takes no value. incr requires a numeric value. Use --etag with the actual ETag read from the item to protect a conditional update.

Delete an exact item safely

Warning

Deleting items, containers, or databases removes data. Back up important data, verify the account and target, and review a dry run before applying a deletion.

An rm pattern matches the partition key by default, not the item ID. Use an exact ID, --key=id, and the complete partition key to target one item:

rm sample-1 --key=id --partition-key=demo --database=ShellDemo --container=Items --dry-run

Require a count of one and verify the returned ID, partition key, and ETag. To delete only that reviewed version, repeat the same target without --dry-run and add --etag with the actual returned ETag, preserving its embedded double quotes. Stop on a mismatch; don't retry without the condition. After deletion, use a point read of the same ID and partition key to confirm that the item isn't found. Inspect uncertain outcomes before retrying.

Wildcard or unscoped matches can scan many items and consume substantial RUs. Supplying --partition-key limits both the preview and deletion to that logical partition. rmcon, rmdb, and delete also support --dry-run.

Transactions and bulk operations

Capability batch bulk
Atomicity All operations succeed or roll back together. Each operation succeeds or fails independently; no rollback.
Partition scope One complete partition key. Operations can use different partition keys.
Workload size 1-100 operations per execution, subject to service limits. Streamed input files; stateful jobs are limited to 10,000 operations and 64 MiB of canonical JSON.
Execution One transaction. Bounded concurrent writes; default concurrency is 16.

Both commands accept operations with op values create, upsert, replace, delete, or patch. bulk additionally accepts per-operation partitionKey and conditional ifMatch for replace, delete, and patch. create and upsert don't accept ifMatch.

batch

Run a transaction in one call:

batch run '[{"op":"create","item":{"id":"batch-1","tenantId":"demo","status":"new"}},{"op":"patch","id":"batch-1","operations":[{"op":"set","path":"/status","value":"ready"}]}]' --partition-key=demo --database=ShellDemo --container=Items

For interactive construction, use begin, add, status, show, execute, and cancel. The active batch holds its target and partition key. Through MCP, only one-shot batch run is supported.

bulk

Use bulk run <json-or-file> for independent operations. It accepts a JSON array, JSON Lines file, or piped operations. Preview a plan before allowing writes:

bulk run operations.jsonl --database=ShellDemo --container=Items --dry-run

operations.jsonl can contain one operation per line, for example:

{"op":"create","item":{"id":"bulk-1","tenantId":"demo","status":"new"}}
{"op":"create","item":{"id":"bulk-2","tenantId":"other","status":"new"}}

After review, apply the same file with --yes. Add --journal=<file> for resumable execution. A journal skips succeeded writes, retries failed writes, and holds back operations with uncertain outcomes. Inspect uncertain results before using --retry-uncertain; replaying non-idempotent operations can duplicate effects.

Option Purpose
--concurrency Bound in-flight writes. Higher concurrency doesn't increase provisioned throughput.
--continue-on-error Continue scheduling writes after individual operation failures.
--max-items Bound query-selected items for bulk patch or bulk delete.
--max-ru Set an observed-RU budget, not an exact billing cap; in-flight work can still complete.
--dry-run Validate input or select items without database writes. Selection can consume RUs.
--etag Capture conditional ETags for query-selected patch or delete operations.
--save Write a query-selected plan to a new file for separate review and execution.

bulk patch --where <predicate> --operations <json> and bulk delete --where <predicate> select items with an Azure Cosmos DB query predicate over alias c. They aren't SQL update or delete statements. With --save, selection produces a reviewable snapshot instead of requiring a new selection at execution.

Interactive stateful jobs use begin, add, status, show, execute, and cancel. MCP supports only run, patch, and delete. Partial failures don't undo successful writes; inspect the summary before retrying.

Import and export

export items.json --database=ShellDemo --container=Items --max=100
export items.csv --database=ShellDemo --container=Items --max=100
import items.json --database=ShellDemo --container=Items --dry-run

export writes a JSON array, or CSV when the destination name ends in .csv. It doesn't write the query-result envelope or JSON Lines. --query selects a subset, --max bounds output, and --force permits replacing an existing destination only after successful export.

import detects JSON arrays, single objects, and object sequences, including JSON Lines. A .csv extension selects CSV; values are imported as strings. CSV uses a semicolon separator by default; set the COSMOSDB_SHELL_CSVSEP environment variable when another separator is required. --format on either command changes the summary presentation, not the file format.

import --dry-run validates input syntax and item IDs offline, without target requests or writes. It doesn't verify the target partition key, permissions, ID conflicts, or all service constraints. A successful dry run reports validated records and imported: 0.

To apply a validated file, remove --dry-run. The default mode inserts items; --mode=upsert can overwrite them. Imports default to 16 concurrent writes. Use --concurrency=1 when file order matters. --continue-on-error continues after individual write failures, not malformed input. Successful earlier writes aren't rolled back, and in-flight writes can finish after a failure.

Interactive import, bulk, and pattern-based removal display periodic progress. Structured output and MCP responses retain their result shapes without terminal progress text.

Database and container management

Command Purpose
mkdb <name> Create a database at account-root scope; use --scale=manual or --scale=auto with --ru for throughput settings.
mkcon <name> <partition-key-path> [unique-key-paths] Create a container; hierarchical paths are comma-separated positional paths.
create database / create container Generic creation forms.
rmdb <name> / rmcon <name> Remove a database or container.
delete database / delete container / delete item Generic deletion forms.
cd
info --format=json
ls
mkdb ShellDemo --scale=auto --ru=1000
cd /ShellDemo
mkcon Items /tenantId --scale=manual --ru=400

Verify the account and choose an unused database name before running mkdb. Run each creation command separately and check its result before continuing. mkdb requires account-root scope; mkcon runs from the database scope selected by cd /ShellDemo.

These settings allocate throughput and can incur charges. On serverless accounts, omit --scale and --ru; throughput settings aren't supported there.

On provisioned accounts in version 1.1.295, omitting throughput options creates shared autoscale throughput for a database, or dedicated autoscale throughput for a container, with a default maximum of 1,000 RU/s. Specify your intended settings rather than relying on version-dependent defaults.

Management operations prefer Azure Resource Manager when connected with supported Microsoft Entra credentials and available ARM context. Key, emulator, and static-token connections use the data plane. ARM creation results report created: null and outcome: "createdOrUpdated"; they don't prove that a resource was newly created.

Container policies and throughput

Command Subcommands and purpose
index (alias indexpolicy) show, add, remove, or set indexing paths and policies.
throughput show, set / manual, or autoscale provisioned RU/s.
ttl show, set <seconds>, on without a default expiration, or off.
conflict show or set last-writer-wins or custom conflict resolution.
bucket Select a client throughput bucket, or show, set, and clear container bucket limits.

Read configuration before making changes:

index show --database=ShellDemo --container=Items
throughput show --database=ShellDemo --container=Items
throughput autoscale 1000 --database=ShellDemo --container=Items --dry-run
ttl show --database=ShellDemo --container=Items
conflict show --database=ShellDemo --container=Items

Index changes affect query behavior and indexing cost. TTL changes can expire existing items. Conflict-resolution policies apply to multi-region write accounts.

Throughput changes can affect charges. Serverless accounts and containers using database-shared throughput don't have dedicated container throughput to change. Switching manual/autoscale modes requires supported token-based management; key-based connections can't perform that migration.

bucket <0-5> changes this client's selection; 0 clears it. Container bucket limits require an Entra management connection and provisioned throughput. They aren't available over key or emulator connections.

Server-side programming and change feed

Command Purpose
sproc list, show, exists, create, exec, edit, or delete stored procedures.
udf list, show, exists, create, edit, or delete user-defined functions.
trigger list, show, exists, create, edit, or delete triggers.
watch (alias tail) Read new and modified items from a container's change feed.

sproc exec requires a complete --partition-key. Create commands accept JavaScript files; interactive create/edit workflows can open an external editor. These programming commands aren't exposed through MCP.

watch --database=ShellDemo --container=Items --max=10

watch consumes RUs and can wait for changes. Stop it with Ctrl+C. It isn't available through MCP.

Pipelines, scripting, and appearance

Command or feature Purpose
filter <expression> Transform piped JSON with the built-in jq-inspired subset.
ftab Render piped JSON as a formatted table.
jq Invoke an installed external jq executable.
cat, dir, edit Read files, list local files, or open a local file in an external editor.
echo Write text or JSON into a pipeline.
exec Execute a shell script.
theme list, show, use, load, validate, save, or edit terminal themes.
az Invoke an installed Azure CLI executable.
help, version, welcome, cls / clear, exit Discover commands and control the shell session.
schema --database=ShellDemo --container=Items --fields-only | filter '.fields' | ftab
theme list
theme use dark

filter isn't a complete jq implementation. It operates on structured pipeline data; inspect a command's result shape before choosing a field path.

Scripts support variables, conditions, loops, and functions. Their syntax belongs to Azure Cosmos DB Shell, not Bash or PowerShell. Multi-line input continues for unclosed constructs or an explicit trailing backslash.

CLI startup options

Run these commands from your operating-system terminal:

cosmosdbshell --version
cosmosdbshell --mcp
cosmosdbshell --mcp 6129
cosmosdbshell --connect https://<account-name>.documents.azure.com/ --connect-tenant=<tenant-id>

Connection options use the --connect- prefix at startup, such as --connect-managed-identity, --connect-subscription, and --connect-resource-group. Use --otel to enable OpenTelemetry tracing; configure export according to the upstream shell guide.

AI tools

Use these actions to look up Shell commands with your assistant.

For documentation-only retrieval, use the Microsoft Learn MCP server. For a compact guide index, use the Shell documentation index (llms.txt). The index doesn't change crawler permissions or guarantee retrieval.

Shell MCP requires separate setup and can read or change data under the configured permissions, so review tool calls before approving them. Don't share credentials or sensitive data.

Connect your AI agent
Configure Shell MCP for authenticated database operations.

Read as Markdown
Open a text version to copy into your assistant.

Ask ChatGPT
Find command syntax and identify data-changing operations.

Ask Claude
Find command syntax and identify data-changing operations.

ChatGPT and Claude receive only the public article URL and a starter prompt. You might need to sign in. If retrieval fails, copy the Markdown text. These links don't configure database access.