You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#管理带分区键的Azure Cosmos DB Mongo API集合?

在Azure Cosmos DB(Mongo API)中创建带分区键的集合的最佳方案

问题分析

你当前使用GetCollection方法时无法指定分区键,尝试的RunCommand方案失败核心原因是shardKey参数格式错误,且本地Mongo容器不支持Cosmos DB特有的customAction命令,因此本地测试报错属于预期情况。

解决方案1:修正RunCommand的shardKey格式

Cosmos DB的Mongo API要求shardKey必须是BsonDocument类型(需指定键名和排序方向,通常用1表示升序),而非单纯的字符串。修正后的代码如下:

var bson = new BsonDocument
{
    { "customAction", "CreateCollection" },
    { "collection", "MyDocuments" }, // 替换为你的目标集合名
    { "shardKey", new BsonDocument("<ShardKeyName>", 1) }, // 替换为你的分区键名
    { "offerThroughput", 400 } // 按需调整吞吐量
};
var shellCommand = new BsonDocumentCommand<BsonDocument>(bson);
db.RunCommand(shellCommand);
  • 注意:该命令仅适配Azure Cosmos DB的Mongo API,本地Mongo容器不识别customAction,因此本地测试报错无需在意;执行完成后可在Azure门户的Cosmos DB资源中验证分区键是否配置成功。

解决方案2:通过Terraform提前创建集合(推荐)

既然你已经用Terraform部署Cosmos DB,建议直接在Terraform配置中定义集合并指定分区键,实现基础设施即代码的统一管理,避免代码中动态创建集合的复杂度。

示例Terraform配置:

resource "azurerm_cosmosdb_mongo_collection" "my_documents" {
  name                = "MyDocuments"
  resource_group_name = azurerm_cosmosdb_account.example.resource_group_name
  account_name        = azurerm_cosmosdb_account.example.name
  database_name       = azurerm_cosmosdb_mongo_database.example.name

  shard_key {
    path  = "/<ShardKeyName>" // 替换为你的分区键路径(注意前缀/)
    order = "Ascending"
  }

  throughput = 400 // 按需调整吞吐量
}

配置生效后,代码中直接调用GetCollection即可,无需额外创建逻辑:

public IMongoCollection<MyDocument> MyDocumentsCollection =>
         Database.GetCollection<MyDocument>("MyDocuments", mongoCollectionSetting);

解决方案3:确认Cosmos DB Mongo API版本兼容性

确保你的Cosmos DB账户使用Mongo API 3.6及以上版本,低版本对分区键创建命令的支持存在限制,可在Azure门户的Cosmos DB账户概述页查看当前API版本。


内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 01:32:02