How to create indexes in MongoDB via .NET

I've programmatically created a new document collection using the MongoDB C# driver.

At this point I want to create and build indexes programmatically. How can I do that?


Solution 1:

Starting from v2.0 of the driver there's a new async-only API. The old API should no longer be used as it's a blocking facade over the new API and is deprecated.

The currently recommended way to create an index is by calling and awaiting CreateOneAsync with an IndexKeysDefinition you get by using Builders.IndexKeys:

static async Task CreateIndexAsync()
{
    var client = new MongoClient();
    var database = client.GetDatabase("HamsterSchool");
    var collection = database.GetCollection<Hamster>("Hamsters");
    var indexKeysDefinition = Builders<Hamster>.IndexKeys.Ascending(hamster => hamster.Name);
    await collection.Indexes.CreateOneAsync(new CreateIndexModel<Hamster>(indexKeysDefinition));
}

Solution 2:

you should use CreateIndex as EnsureIndex is marked obsolete for future compatibility with the next versions of MongoDB:

var client = new MongoClient("mongodb://localhost");
var db = client.GetServer().GetDatabase("db");
var collection = db.GetCollection<Hamster>("Hamsters");

collection.CreateIndex(IndexKeys<Hamster>.Ascending(_ => _.Name));