Search code examples
c#.netmongodbindexingmongodb-.net-driver

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

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