AGENT SKILL

Cosmos DB MongoDB 最佳实践

cosmosdb-mongodb

Azure Cosmos DB for MongoDB(RU 计费模式)的最佳实践。在以下情况使用此技能:(1) 创建或修改数据库索引,(2) 编写数据库迁移,(3) 设计针对 CosmosDB 的查询,(4) 排查查询性能或索引错误。

适用职业数据工程师
使用场景数据库管理
License 许可
MIT
所属仓库
microsoft/scope
最近更新
2026-11-14
Stars
★ 86
Forks
32

01 前言 Front Matter

name
cosmosdb-mongodb
metadata
{ "version": "1.0.0" }
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.

03 SKILL.md 正文

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:

// ✅ 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:

// ✅ 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:

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:

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:

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:

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

04 同仓库更多 Skills

microsoft
microsoft/scope

agentic-workflows

Route gh-aw design, creation, diagnosis, patching, active debugging, upgrades, and local SDLC issue requests to the right strategies.

★ 86
microsoft
microsoft/scope

github-actions

Use when creating, editing, reviewing, or troubleshooting GitHub Actions workflows in Scope.

★ 86
microsoft
microsoft/scope

AX 智能体体验评估

ax-practitioner

当用户询问 AX(agent experience,智能体体验)或 AX Practitioner Playbook(AX 实践者手册)相关问题时,应使用本技能,例如"如何评估我的技术的智能体体验"、"编写 AX 评估标准"、"设计评估场景"、"propensity 与 efficacy 的区别"、"lift 与 drag"、"应该测试哪些智能体画像"、"需要多少次评估运行"、"如何解读智能体轨迹"、"为什么智能体忽略我的 MCP server 或 skill"、"智能体使用了过时的 SDK 版本"、"扩展太多"、"如何解读 AX readout"、"如何让负责团队修复文档"、"对照检查清单审查我的评估",或 SPFx 实战示例。本技能以交互方式严格依据手册作答并引用章节。当手册中没有答案时,会明确说明,并清楚标注任何通用知识或网络内容。

AI 工程师智能体开发
★ 86
microsoft
microsoft/scope

TypeScript 代码开发规范

typescript

本 monorepo 的 TypeScript 最佳实践。适用本技能的场景:(1) 编写新的 TypeScript 代码,(2) 审查 TypeScript 代码,(3) 处理 API 响应、fetch 调用或 JSON 解析,(4) 添加或修改类型和接口。

软件开发工程师代码实现
★ 86
microsoft
microsoft/scope

Storybook 组件目录维护

storybook

为门户应用维护 Storybook 组件目录。适用本技能的场景:(1) 为组件添加新的 story,(2) 组件变更后更新现有 story,(3) 在 AI 辅助下运行完整的 Storybook 刷新/同步。

软件开发工程师前端开发与界面实现
★ 86
microsoft
microsoft/scope

Scope 基准平台 CLI 操作

scope-cli

使用 Scope CLI 与 Scope 基准测试平台交互——提交运行、列出结果、管理评判标准、生成报告,以及管理智能体、技能和 MCP 服务器。

AI 工程师AI 平台资源管理
★ 86