MongoDB C# Driver Create Index
The new way in the MongoDB 2.7 driver is to do the following:
var notificationLogBuilder = Builders<NotificationLog>.IndexKeys;
var indexModel = new CreateIndexModel<NotificationLog>(notificationLogBuilder.Ascending(x => x.TimestampUtc));
// .NET Full framwork:
await IMongoCollection.Indexes
.CreateOneAsync(indexModel, cancellationToken: cancellationToken)
.ConfigureAwait(false);
// .NET Core:
await IMongoCollection.Indexes
.CreateOneAsync(indexModel, cancellationToken: cancellationToken)
There is a not type safe method for a BsonDocument with the index options here:
var indexBuilder = Builders<BsonDocument>.IndexKeys;
var keys = indexBuilder.Ascending("timestamp");
var options = new CreateIndexOptions
{
Name = "expireAfterSecondsIndex",
ExpireAfter = TimeSpan.MaxValue
};
var indexModel = new CreateIndexModel<BsonDocument>(keys, options);
// .NET full framework
await collection.Indexes
.CreateOneAsync(indexModel, cancellationToken: cancellationToken)
.ConfigureAwait(false);
// .NET Core
await collection.Indexes
.CreateOneAsync(indexModel, cancellationToken: cancellationToken);