如何通过 .NET 在 MongoDB 中创建索引 [英] How to create indexes in MongoDB via .NET
问题描述
我已经使用 MongoDB C# 驱动程序以编程方式创建了一个新的文档集合.
I've programmatically created a new document collection using the MongoDB C# driver.
此时我想以编程方式创建和构建索引.我该怎么做?
At this point I want to create and build indexes programmatically. How can I do that?
推荐答案
从驱动程序的 v2.0 开始,有一个新的 async
-only API.不应再使用旧 API,因为它是新 API 的阻塞外观,已弃用.
Starting from v2.0 of the driver there's a new async
-only API. The old API should no longer be used as it's a blocking facade over the new API and is deprecated.
当前推荐的创建索引的方法是通过使用 Builders.IndexKeys
调用并等待 CreateOneAsync
和 IndexKeysDefinition
:
The currently recommended way to create an index is by calling and awaiting CreateOneAsync
with an IndexKeysDefinition
you get by using Builders.IndexKeys
:
static async Task CreateIndexAsync()
{
var client = new MongoClient();
var database = client.GetDatabase("HamsterSchool");
var collection = database.GetCollection<Hamster>("Hamsters");
var indexKeysDefinition = Builders<Hamster>.IndexKeys.Ascending(hamster => hamster.Name);
await collection.Indexes.CreateOneAsync(new CreateIndexModel<Hamster>(indexKeysDefinition));
}
这篇关于如何通过 .NET 在 MongoDB 中创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!