Search code examples
c#mongodb-.net-driver

MongoDB C# Driver Create Index


I just updated my MongoDB from version 2.5.0 to 2.7.0. Visual Studio tells me that the following way to create an index is obsolete:

protected override Task OnPerformMaintenanceAsync(CancellationToken cancellationToken) 
    => NotificationLogs.Indexes
                       .CreateOneAsync(Builders<NotificationLog>.IndexKeys
                                                                .Ascending(_ => _.TimestampUtc));

It suggests me to use CreateIndexModel.

The only problem is that I cannot find an example to get this working that will do the same.

I tried:

protected Task OnPerformMaintenanceTestAsync(CancellationToken cancellationToken)
{
  // Old approach
  var builder = Builders<NotificationLog>.IndexKeys
                                         .Ascending(x => x.TimestampUtc);

  // New approach
  var indexModel = new CreateIndexModel<NotificationLog>(nameof(NotificationLog.TimestampUtc));
  
  return NotificationLogs.Indexes.CreateOneAsync(indexModel);
}

But I get the following exception:

System.FormatException: 'JSON reader was expecting a value but found 'TimestampUtc'.'


Solution

  • 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:
    // .NET Standard library:
    await IMongoCollection.Indexes
                          .CreateOneAsync(indexModel, cancellationToken: cancellationToken)
                          .ConfigureAwait(false);
    
    // .NET Core:
    await IMongoCollection.Indexes
                          .CreateOneAsync(indexModel, cancellationToken: cancellationToken)