Search code examples
c#mongodbasp.net-coreazure-cosmosdbazure-cosmosdb-mongoapi

Add compound Index to MongoDB API in Cosmos


I am using sorting in my application and using cosmos mongodb api as database. I have created wildcard index in the code to accommodate the sorting but somehow I am still getting the error as compound index is missing. Here is how I am creating the index.

 var wcIndex = new IndexKeysDefinitionBuilder<T>().Wildcard();
 var wcIndexModel = new CreateIndexModel<T>(wcIndex, options);
 _collection = _database.GetCollection<T>(_collectionName);
 _collection.Indexes.CreateOneAsync(wcIndexModel);

and the error am getting is

The index path corresponding to the specified order-by item is excluded / The order by query does not have a corresponding composite index that it can be served from.

Is there anyway I can add composite index for model to get the sorting done ?


Solution

  • I have added the below code to make it work for using sorting in mongo Cosmos API.

     IndexKeysDefinition<T> keys =  "{'$**': 1}";
     var wildcardIndex = new CreateIndexModel<T>(keys);
    _collection = _database.GetCollection<T>(_collectionName);
    _collection.Indexes.CreateOne(wildcardIndex);