Search code examples
mongodbazure-cosmosdbsharding

Sharded collections and MongoDb


I've created a sharded collection on Cosmos (for use with C# MongoDB driver) through the portal. Created using Data Explorer -> New Collection - Shard Key set at this point.

I've set the shard key to be partitionId.

As an example when trying to insert this document into a collection named "data":

db.data.insert({partitionId:"test"})

I receive the error Command insert failed: document does not contain shard key.


Solution

  • Edit:

    There seem to be issues when creating the sharded collection using the portal. Manually creating the sharded collection should work, see: https://stackoverflow.com/a/48202411/5405453

    Original:

    From the docs:

    The shard key determines the distribution of the collection’s documents among the cluster’s shards. The shard key is either an indexed field or indexed compound fields that exists in every document in the collection.

    On creation of the sharded collection, you have provided a key which should be used as shard key. Next if you insert a document it has to contain that key. See here.