Search code examples
c#mongodbazureazure-cosmosdbmongodb-indexes

MongoDB Indexes.CreateOneAsync Exception using Azure DocumentDB


I'm trying to create multiple unique indexes using c# MongoDB driver connecting to Azure DocumentDB instance, but I'm receiving the following exception when trying to create the second unique index:

MongoDB.Driver.MongoCommandException: 'Command createIndexes failed: Message: {"Errors":["The number of unique keys cannot be greater than 1."]}

I can't seem to find any documentation regarding the number of unique keys for Azure DocumentDB collection. Note that this exception does not occur when using actual MongoDB instance.

var keys = Builders<ProductEntity>.IndexKeys.Ascending(p => p.UPC);
var options = new CreateIndexOptions<ProductEntity>() { Name = "UX_UPC", Unique = true, Sparse = true };
var result = await _collection.Indexes.CreateOneAsync(keys, options);

keys = Builders<ProductEntity>.IndexKeys.Ascending(p => p.Manufacturer).Ascending(p => p.MPN);
options = new CreateIndexOptions<ProductEntity>() { Name = "UX_Manufacturer_MPN", Unique = true, Sparse = true };
result = await _collection.Indexes.CreateOneAsync(keys, options);

public class ProductEntity
{
    public Guid Id { get; set; }
    public string UPC { get; set; }
    public string MPN { get; set; }
    public string Manufacturer { get; set; }
}

Solution

  • From this blog, we could find it does not support for Unique indexes currently.

    General availability is just the beginning for all the features and improvements we have in stored for DocumentDB: API for MongoDB. In the near future, we will be releasing support for Unique indexes and a couple major performance improvements.

    This thread discussed Cannot create index in Azure DocumentDb with Mongodb protocol, you could refer to it.