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