简体   繁体   中英

Azure Cosmos MongoDB - Create collection with shard key

I need to create a collection in Azure's Cosmos MongoDB but with a partition/shard key as the required configuration is that the database will have a provisioned throughput (a set amount of RU's) and the collections in it will have a shared throughput.

The cluster's API is set to Cosmos DB Mongo API - If i create the collection in the cosmos i have no issues with Insert/Delete, but if i create the collection using the code below i will get an error saying {"Command insert failed: document does not contain shard key."} even though viewing the collection made in the portal and in the code look identical.

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

I have talked to a microsoft representative but i get lacking "answers". He advised to use Mongo CSharp Driver but it seems this driver is unable to define a partition key (which makes sense).

How can i create a collection with a partition key?

Thank you.

You can use customCommand to create a collection with ShardKey. Something likes this:

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

I was dealing with the same thing. When using MongoDB csharp driver you should not call db.CreateCollection, but use sharding command instead. This will create your unlimitted collection with the partition key for you.

//Sharded collection must be initialized this way
var bson = new BsonDocument
{
    { "shardCollection", mongoClientProvider.DatabaseName + "." + CollectionName },
    { "key", new BsonDocument(ShardKeyName, "hashed") }
};

var shellCommand = new BsonDocumentCommand<BsonDocument>(bson);

try
{
    var commandResult = database.RunCommand(shellCommand);
}
catch (MongoCommandException ex)
{
    logger.LogError(ex, ex.Result.ToString());
}

I guess you need to do that via command through the mongo shell

db.runCommand( { shardCollection: "yourCollection", key: { rateId: "_id" } } )

Refer here form more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM