Search code examples
c#.netmongodbmongodb-.net-drivermongodb-csharp-2.0

Building indexes in MongoDB with .NET driver 2.0


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.


Solution

  • 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 }");