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.

3
  • 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!? Commented May 6, 2015 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. Commented May 7, 2015 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 Commented May 8, 2015 at 23:52

1 Answer 1

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 }");
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Do you know how to do it for BsonDocument collections?
@BigJoe714 I've updated the post. Does that answer your question?
How to create multiple indexes by using Indexes.CreateMany()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.