使用.NET驱动程序2.0在MongoDB中构建索引

hho*_*tij 10 .net c# mongodb mongodb-csharp-2.0 mongodb-.net-driver

使用新驱动程序2.0构建索引的新方法是什么?没有关于此的任何文档.

显然这现在适用于新的IndexKeysDefinitionBuilder<>界面,但这是我到目前为止所有.

i3a*_*non 19

你需要打电话await CreateOneAsyncIndexKeysDefinition您通过使用得到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));
}
Run Code Online (Sandbox Code Playgroud)

如果你没有a,Hamster你也可以通过指定索引的json表示以非强类型方式创建索引:

await collection.Indexes.CreateOneAsync("{ Name: 1 }");
Run Code Online (Sandbox Code Playgroud)

  • @ BigJoe714我已经更新了帖子.这是否回答你的问题? (2认同)