10

What's the new way to build indexes with the new driver 2.0? There's no documentation whatsoever about this.

Apparently this now works with the new IndexKeysDefinitionBuilder<> interface but that's all I got so far.

i3arnon
  • 113,022
  • 33
  • 324
  • 344
hholtij
  • 2,906
  • 6
  • 27
  • 42
  • 1
    I'm having the same problem after upgrading to 2.0! Why did they feel the need to absolute overcomplicate something that was simple!? – John Doherty May 06 '15 at 14:12
  • I am starting to like it. I can see where the design decisions came from and the usage of builders in this case is consistent with other usages (filter builders, etc). I especially like that they have made everything fully async. It's just (currently at least) not well documented and not easy to get detailed information or samples. – hholtij May 07 '15 at 12:54
  • It's been a couple of days and I'm liking it too, especially the async stuff. It was so many changes with very little documentation that frustrated me, I had to resort to reading the source on github... I'm sure they'll resolve that soon though – John Doherty May 08 '15 at 23:52

1 Answers1

19

You need to call and await CreateOneAsync with an IndexKeysDefinition you get by using Builders.IndexKeys:

static async Task CreateIndex()
{
    var client = new MongoClient();
    var database = client.GetDatabase("db");
    var collection = database.GetCollection<Hamster>("collection");
    await collection.Indexes.CreateOneAsync(Builders<Hamster>.IndexKeys.Ascending(_ => _.Name));
}

If you don't have a Hamster you can also create the index in a non-strongly-typed way by specifying the index's json representation:

await collection.Indexes.CreateOneAsync("{ Name: 1 }");
i3arnon
  • 113,022
  • 33
  • 324
  • 344