如何使用 Mongo API 在共享吞吐量 cosmosdb 中创建集合

How to create a collection in a shared throughput cosmosdb using the Mongo API

我有一个已配置 database-level throughput 的 Azure CosmosDb 数据库。我们正在对这个 Cosmos 实例使用 MongoDB API。共享吞吐量模型要求所有集合都指定一个分区键,这似乎阻止了几乎所有工具都无法创建集合,除了 Azure 门户或官方 Azure Cosmos SDK。例如,在 Robo 3T 中,尝试创建集合会导致以下错误:

Failed to create collection 'mycollection'.

Error: Shared throughput collection should have a partition key

尝试通过 mongoose(类似于 this question)或其他工具创建集合时会发生同样的错误。

所以我想操作问题可以归结为: 有没有办法通过MongoDbAPI将所需的partitionKey传递给CosmosDb,这样集合创建就会成功?

通过 db.runCommand(...)

使用 shardCollection 命令

事实证明, 是一种可行的方法,如果晦涩难懂,可以使用 MongoDb 有线协议实现此目的。您可以使用 Cosmos 分区键(概念上映射到 Mongo 分片键)创建一个集合,方法是发出数据库级命令为尚不存在的集合设置分片键:

在 mongo shell:

db.runCommand({shardCollection: "myDbName.nameOfCollectionToCreate", 
               key: {nameOfDesiredPartitionKey: "hashed"}})

在 运行 之后,我的 ComosDb 数据库(具有数据库级共享吞吐量)现在包含分区键设置正确的新集合!

我还没有想出通过 Mongoose 直接调用 runCommand 的方法,但至少这种 native/wire 协议方法应该适用于任何官方 MongoDb 驱动程序,因此比仅依赖 Azure Cosmos SDK 来创建集合要便携得多。

可以使用扩展命令。

Create collection

CreateCollection命令格式如下:

{
  customAction: "CreateCollection",
  collection: "<Collection Name>",
  shardKey: "<Shard key path>",
  offerThroughput: (int), // Amount of throughput allocated to a specific collection
}

Java脚本

db.runCommand({customAction: "CreateCollection", collection: "testCollection", shardKey: "sharedKeyName"});

Java

BasicDBObject testCollection = new BasicDBObject("customAction", "CreateCollection")
                            .append("collection", "testCollection")
                            .append("shardKey", "sharedKeyName");
db.runCommand(testCollection);