---
name: cosmosdb-mongodb
description: >-
  Best practices for Azure Cosmos DB for MongoDB (RU-based). Use this skill when: (1) creating or modifying database indexes, (2) writing database migrations, (3) designing queries against CosmosDB, (4) troubleshooting query performance or index errors.
metadata:
  version: "1.0.0"
title: cosmosdb-mongodb
canonical_url: https://skilld.dev/gh/microsoft/scope/cosmosdb-mongodb
last_updated: 2026-10-19T12:45:47.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install microsoft/scope/cosmosdb-mongodb`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/cosmosdb-mongodb`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/microsoft/scope/cosmosdb-mongodb) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/cosmosdb-mongodb`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/cosmosdb-mongodb --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/cosmosdb-mongodb --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Azure Cosmos DB for MongoDB (RU-based) Best Practices

## Indexing Strategy

### Prefer Single-Field Indexes for Equality Filters

Cosmos DB uses **index intersection** for multi-property equality filters. Create single-field indexes on each filtered field rather than large compound indexes:

```typescript
// ✅ GOOD — single-field indexes, Cosmos intersects them for queries with multiple filters
await col.createIndex({ "run.status": 1 });
await col.createIndex({ workerType: 1 });
await col.createIndex({ deletedAt: 1 });

// ❌ BAD — large compound index may be silently ignored by Cosmos DB
await col.createIndex({ "run.status": 1, workerType: 1, deletedAt: 1, priority: -1, createdAt: 1 });
```

### Use 2-Field Compound Indexes for ORDER BY

Cosmos DB requires a compound index that matches the sort fields. Keep it to **2 fields maximum** for reliability:

```typescript
// ✅ GOOD — 2-field compound for sort, single-field indexes handle the WHERE clause
await col.createIndex({ priority: -1, createdAt: 1 });

// ✅ GOOD — selective filter + sort field compound
await col.createIndex({ "run.postProcessorStatus": 1, updatedAt: -1 });
```

### Large Compound Indexes May Be Silently Dropped

Cosmos DB (RU-based) **silently drops compound indexes** it cannot support — `createIndex()` succeeds but the index is never created. This leads to runtime errors like:

```
"The order by query does not have a corresponding composite index that it can be served from."
```

**Always verify** that your index was actually created:

```javascript
db.collection.getIndexes()
```

### Index Pattern for Polling Queries

For queries that combine equality filters with a sort (e.g., scheduler dispatchers), use this pattern:

1. Single-field indexes on each equality filter field (from migration 009)
2. A focused 2-field compound index: `{ mostSelectiveFilterField: 1, sortField: -1 }`

## Migration Best Practices

### Structure

Migrations live in `packages/db-migrations/src/migrations/` and implement `MigrationInterface` from `mongo-migrate-ts`:

```typescript
import type { Db } from "mongodb";
import type { MigrationInterface } from "mongo-migrate-ts";

export class MyMigration implements MigrationInterface {
  async up(db: Db): Promise<void> { /* ... */ }
  async down(db: Db): Promise<void> { /* ... */ }
}
```

### Always Wrap Index Operations in try/catch

Index creation or deletion may fail if the index already exists or doesn't exist. Never let this crash the migration:

```typescript
try {
  await col.createIndex({ field: 1 });
  console.log("[NNN] Created index on field");
} catch (err: any) {
  console.log(`[NNN] Index already exists or couldn't be created: ${err.message ?? err}`);
}
```

### Register in required-migrations.ts

Every new migration must be added to `packages/db-migrations/src/required-migrations.ts`. The API readiness probe checks that all required migrations have been applied.

### down() Should Be Safe but Not Destructive

Dropping indexes in `down()` can be destructive in production. Prefer a log-only approach:

```typescript
async down(db: Db): Promise<void> {
  console.log("[NNN-down] Skipping index drop — indexes should be dropped manually if needed");
}
```

## Features NOT Supported or Limited

These MongoDB features do **not** work reliably in Cosmos DB for MongoDB (RU-based):

| Feature | Status |
|---------|--------|
| Large compound indexes (5+ fields) | May be silently ignored |
| `$text` / text indexes | Not supported |
| Certain aggregation stages | Partial support — test each one |
| Change streams (resume after) | Limited compared to native MongoDB |
| Transactions (multi-document) | Supported only on API version 4.0+ with limitations |

## RU Cost Awareness

- Every index increases write RU cost (each insert/update/delete must update all indexes)
- Keep the total number of indexes reasonable — add indexes only for queries that actually run
- Compound indexes cost more RUs per write than single-field indexes
