首页 > 解决方案 > Azure Cosmos MongoDB - 使用分片键创建集合

问题描述

我需要在 Azure 的 Cosmos MongoDB 中创建一个集合,但需要使用分区/分片键,因为所需的配置是数据库将具有预配置的吞吐量(一组 RU),并且其中的集合将具有共享的吞吐量。

集群的 API 设置为Cosmos DB Mongo API- 如果我在 cosmos 中创建集合,则插入/删除没有问题,但如果我使用下面的代码创建集合,{"Command insert failed: document does not contain shard key."}即使查看在门户中创建的集合,我也会收到错误消息,并且在代码中看起来相同。

client.CreateDocumentCollectionAsync(database.SelfLink,
new DocumentCollection
{
    Id = "CollectionName",
    PartitionKey = new PartitionKeyDefinition { Paths = new Collection<string> { "/_id" } }
}).Wait();

我已经与微软代表谈过,但我缺乏“答案”。他建议使用Mongo CSharp Driver,但似乎这个驱动程序无法定义分区键(这是有道理的)。

如何使用分区键创建集合?

谢谢你。

标签: c#azure-cosmosdbazure-cosmosdb-mongoapi

解决方案


您可以使用customCommand创建带有 ShardKey 的集合。像这样的东西:

var createCollectionCommand = new BsonDocument
                {
                    { "customAction", "CreateCollection" },
                    { "collection", "YourCollectionName" },
                    { "shardKey", "YourShardKey" }
                };
cosmosDatabase.RunCommand<BsonDocument>(createCollectionCommand);

推荐阅读