Create a sharded MongoDB in Azure Cosmos DB

During my last project I was setting up a Release Pipeline in VSTS and one of the steps was to create a Sharded MongoDB in Cosmos DB.

I am a big fan of the Azure CLI, which I use quiet often.

I started to create in bash an Azure CLI script but soon I discovered that it was not working well. The script gave no errors, everything seemed to be ok, but I was getting an error when inserting a document that the sharded key was not found/provided.

I created a stackoverflow thread to describe the problem.
After having contact with Microsoft they confirmed there’s indeed a bug in the actual version of the Azure CLI (2.0.21) and to solve the problem the partition (shard) key string should use the “$v” pattern to make everything working.

So here is the final working bash script to be able to create a sharded MongoDB:


#!/bin/bash
resourceGroupName="cosmosdbshardedtest"
name="mongodboncosmosdb"
databaseName="mongodb"
collectionName="mongodbcoll"
kind="MongoDB"
partition="/'\$v'/YourShardID/'\$v'"
az login
az group create –name $resourceGroupName –location westeurope
az cosmosdb create –name $name –kind $kind –resource-group $resourceGroupName
az cosmosdb database create –name $name –db-name $databaseName –resource-group $resourceGroupName
az cosmosdb collection create –collection-name $collectionName –name $name –db-name $databaseName –resource-group $resourceGroupName –partition-key-path $partition

The important part is actually this:

partition="/'$v'/YourShardID/'$v'"

Where /YourShardID should be replaced with the document property you want to use for the partitioning.

Conclusion

Use the “$v” pattern described above to define you partition, until Microsoft will come with a new release of the Azure CLI with a fix.

 

One thought on “Create a sharded MongoDB in Azure Cosmos DB

Add yours

  1. Great article! I wan’t to establish sharding in Azure cosmosdb. As i’m using it as mongo wrapper in cloud. Could please point me into right direction?

    Thanks a lot

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at WordPress.com.

Up ↑

%d bloggers like this: