How to create indexes in MongoDB via .NET

C#.NetMongodbIndexingMongodb .Net-Driver

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

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

Solution 2 - C#

you should use CreateIndex as EnsureIndex is marked obsolete for future compatibility with the next versions of MongoDB:

var client = new MongoClient("mongodb://localhost");
var db = client.GetServer().GetDatabase("db");
var collection = db.GetCollection<Hamster>("Hamsters");

collection.CreateIndex(IndexKeys<Hamster>.Ascending(_ => _.Name));

Solution 3 - C#

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<Hamster>("Hamsters");
	var indexOptions = new CreateIndexOptions();
	var indexKeys = Builders<Hamster>.IndexKeys.Ascending(hamster => hamster.Name);
	var indexModel = new CreateIndexModel<Hamster>(indexKeys, indexOptions);
	await collection.Indexes.CreateOneAsync(indexModel);
}

Solution 4 - C#

Something like this should do:

var server = MongoServer.Create("mongodb://localhost");
var db = server.GetDatabase("myapp");

var users = db.GetCollection<User>("users");

users.EnsureIndex(new IndexKeysBuilder().Ascending("EmailAddress"));

Please see the following bits in the documentation:

Solution 5 - C#

There is an entire area on Indexing under the Definitions and Builders documentation page:

http://mongodb.github.io/mongo-csharp-driver/2.4/reference/driver/definitions/#index-keys

Example:

IndexKeysDefinition<MyModel> keys = "{ Reference: 1 }";
var indexModel = new CreateIndexModel<MyModel>(keys);
await _context.Indexes.CreateOneAsync(indexModel);

Solution 6 - C#

the easiest way to create indexes in c# is by using the driver wrapper library MongoDB.Entities. here's an example of creating a text index:

    DB.Index<Author>()
      .Key(a => a.Name, Type.Text)
      .Key(a => a.Surname, Type.Text)
      .Create();

and to do a full-text search, you simply do:

    DB.SearchText<Author>("search term");

haven't seen anything else that makes it simpler than that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPayedimauntView Question on Stackoverflow
Solution 1 - C#i3arnonView Answer on Stackoverflow
Solution 2 - C#i3arnonView Answer on Stackoverflow
Solution 3 - C#Stephen KennedyView Answer on Stackoverflow
Solution 4 - C#DerickView Answer on Stackoverflow
Solution 5 - C#CraigView Answer on Stackoverflow
Solution 6 - C#Dĵ ΝιΓΞΗΛψΚView Answer on Stackoverflow