How to create indexes in MongoDB via .NET

后端 未结 6 981
有刺的猬
有刺的猬 2020-12-08 18:23

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

6条回答
  •  温柔的废话
    2020-12-08 19:12

    The overload of CreateOneAsync in the currently accepted answer is now marked as obsolete with the message "Use CreateOneAsync with a CreateIndexModel instead." Here's how you do it:

    static async Task CreateIndex(string connectionString)
    {
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("HamsterSchool");
        var collection = database.GetCollection("Hamsters");
        var indexOptions = new CreateIndexOptions();
        var indexKeys = Builders.IndexKeys.Ascending(hamster => hamster.Name);
        var indexModel = new CreateIndexModel(indexKeys, indexOptions);
        await collection.Indexes.CreateOneAsync(indexModel);
    }
    

提交回复
热议问题