Create a sharded MongoDB in Azure Cosmos DB

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.