Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building indexes in MongoDB with .NET driver 2.0

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

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

like image 315
hholtij Avatar asked Apr 08 '15 01:04

hholtij


People also ask

Can we create index in MongoDB?

MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index on the _id field.

Can we create multiple indexes in MongoDB?

In order to build multiple indexes at once, you need to use createIndexes() and pass multiple keys into an array.

How are MongoDB indexes stored?

The index data is stored along with the collection data in the data directory of the MongoDB Server installation. You can also specify the data directory using the --dbpath storage option when you start the mongod.

How do you create an index in descending order in MongoDB?

For an ascending index on a field, specify a value of 1 ; for descending index, specify a value of -1 . Starting in 3.6, you cannot specify * as the index name. MongoDB supports several different index types including text, geospatial, and hashed indexes.


1 Answers

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

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 }");
like image 60
i3arnon Avatar answered Oct 06 '22 21:10

i3arnon