2

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.

Stennie
  • 63,885
  • 14
  • 149
  • 175
Tomer Something
  • 770
  • 1
  • 10
  • 24

2 Answers2

3

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());
}
  • 2
    I get `MongoDB.Driver.MongoCommandException: 'Command shardCollection failed: Sharding is not supported for existing collections..'`. – cederlof Oct 01 '19 at 09:32
3

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);
thangcao
  • 1,819
  • 1
  • 13
  • 14