Building indexes in MongoDB with .NET driver 2.0

…衆ロ難τιáo~ 提交于 2019-12-03 11:58:35

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 }");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!