mongodbazure-cosmosdbazure-cosmosdb-mongoapi

Creating unique index for CosmosDB with MongoDB API fails


I'm using Azure CosmosDB with the MongoDB API. I'm trying to execute the following:

db.createCollection('test')
db.test.createIndex({key: 1}, {name: 'key_1', unique: true})

However, doing so fails with the following error:

The unique index cannot be modified. To change the unique index, remove the collection and re-create a new one.

When reading about it in the documentation and on Stack Overflow, it's mentioned that you can only create a unique index for empty collections.

However, when I try the following command, it seems my collection is empty, so this apparantly isn't the reason why it isn't working:

db.test.find()

I tried to recreate the collection several times, but to no avail.


Solution

  • In my case, the problem was caused by a limitation of the continuous backup of CosmosDb.

    As stated in the documentation:

    Azure Cosmos DB API for SQL or MongoDB accounts that create unique index after the container is created aren't supported for continuous backup. Only containers that create unique index as a part of the initial container creation are supported. For MongoDB accounts, you create unique index using extension commands.

    I had to create my unique index using the custom commands.

    db.runCommand({ 
      customAction: "CreateCollection", 
      collection: "CollectionName", 
      indexes: [
        {
          key: { "FieldName": 1 }, 
          name: "FieldName_1", 
          unique: true
        }
      ]
    })