Building indexes in MongoDB with .NET driver 2.0

后端 未结 1 1952
不知归路
不知归路 2021-02-14 07:15

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 IndexKeysDefi

相关标签:
1条回答
  • 2021-02-14 07:24

    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 }");
    
    0 讨论(0)
提交回复
热议问题