与.NET 2.0的驱动程序建立索引在MongoDB中驱动程序、索引、NET、MongoDB

2023-09-03 17:02:59 作者:霸气⑩足

什么是新的方式来与新的驱动程序2.0建立索引? 有没有任何文档关于这个。

What's the new way to build indexes with the new driver 2.0? There's no documentation whatsoever about this.

显然,这个现在可以用新的 IndexKeysDefinitionBuilder<> 接口,但是这是我的一切,到目前为止

Apparently this now works with the new IndexKeysDefinitionBuilder<> interface but that's all I got so far.

推荐答案

您需要打电话等待 CreateOneAsync IndexKeysDefinition 您使用得到 Builders.IndexKeys

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

如果你没有一个仓鼠您还可以通过指定索引的JSON重新presentation创建索引在非强类型的方式:

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