使用.NET驱动程序2.0在MongoDB中构建索引
使用新驱动程序2.0构建索引的新方法是什么? 没有关于此的任何文档。
显然这现在适用于新的IndexKeysDefinitionBuilder
接口,但这是我到目前为止所有。
您需要使用Builders.IndexKeys
调用并await
CreateOneAsync
的IndexKeysDefinition
:
static async Task CreateIndex() { var client = new MongoClient(); var database = client.GetDatabase("db"); var collection = database.GetCollection("collection"); await collection.Indexes.CreateOneAsync(Builders .IndexKeys.Ascending(_ => _.Name)); }
如果您没有Hamster
您还可以通过指定索引的json表示以非强类型方式创建索引:
await collection.Indexes.CreateOneAsync("{ Name: 1 }");