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.
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.
In order to build multiple indexes at once, you need to use createIndexes() and pass multiple keys into an array.
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.
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.
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 }");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With