15

I want to create a compound index where one key should be in ascending, the second key in descending order.

How can I do this?

I have a string containing the property names the user selected.

collection.EnsureIndex(IndexKeys.Descending(selectedProperties[0]),
                IndexKeys.Ascending(selectedProperties[1])),
IndexOptions.......

does not work

i3arnon
  • 113,022
  • 33
  • 324
  • 344
user2010435
  • 173
  • 1
  • 1
  • 6

4 Answers4

14

In v2.x of the driver they completely changed the API so currently the way to create a compound index asynchronously (which is prefered) is:

await collection.Indexes.CreateOneAsync(
    Builders<Hamster>.IndexKeys.Ascending(_ => _.Name).Descending(_ => _.Age),
    new CreateIndexOptions { Background = true });

And synchronously:

collection.Indexes.CreateOne(
    Builders<Hamster>.IndexKeys.Ascending(_ => _.Name).Descending(_ => _.Age),
    new CreateIndexOptions { Sparse = true });
i3arnon
  • 113,022
  • 33
  • 324
  • 344
11

Here's one way:

var keys = new IndexKeysBuilder();

keys.Ascending(keyName1);
keys.Descending(keyName2);

var options = new IndexOptionsBuilder();
options.SetSparse(true);
options.SetUnique(false);
collection.EnsureIndex(keys, options);
WiredPrairie
  • 58,954
  • 17
  • 116
  • 143
6

EnsureIndex is now obsolete, so CreateIndex should be used instead. There are also static builder classes the support fluent usage: IndexKeys and IndexOptions.

So the cleanest option is:

collection.CreateIndex(
    IndexKeys.Ascending(keyName1).Descending(keyName2),
    IndexOptions.SetSparse(true).SetUnique(false));

And for a generic type-safe option:

collection.CreateIndex(
    IndexKeys<Document>.Ascending(d => d.Property1).Descending(d => d.Property2),
    IndexOptions.SetSparse(true).SetUnique(false));
i3arnon
  • 113,022
  • 33
  • 324
  • 344
-1

CreateIndex with

var indexModel = new CreateIndexModel<T>(keys.Ascending(x => x.Property1).Ascending(x=>x.Property2));
                
collection.Indexes.CreateOne(indexModel);
Sasha Kondrashov
  • 4,038
  • 1
  • 18
  • 29
aadreja
  • 1
  • 2
  • thank you for your answer, aadreja. could you please add some text to explain why this is the best answer, or how it works? – Sasha Kondrashov Jul 29 '20 at 00:03
  • @SashaKondrashov - collection.CreateIndex with index keys is obsolete (http://mongodb.github.io/mongo-csharp-driver/2.9/apidocs/html/M_MongoDB_Driver_IMongoIndexManager_1_CreateOne_2.htm). – aadreja Jul 29 '20 at 11:12