Creating unique index for CosmosDB with MongoDB API fails

1.9k Views Asked by At

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.

2

There are 2 best solutions below

1
On

As per the format of the query mentioned, it seems to be like wildcard indexing style and unfortunately if it is true, then wildcard indexing is having limitation in creation of unique index. In Azure Cosmos DB API for MongoDB cannot use wildcard index. Because creating a wildcard index is like executing multiple specific fields.

https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/mongodb-indexing

Refer the above-mentioned link for reference.

0
On

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
    }
  ]
})