Building indexes in MongoDB with .NET driver 2.0

蓝咒 提交于 2019-12-21 03:59:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/29504425/building-indexes-in-mongodb-with-net-driver-2-0

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