Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.'

like image 240
StuiterSlurf Avatar asked Jul 09 '18 14:07

StuiterSlurf


People also ask

Can you use MongoDB with C#?

By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.

Can I use MongoDB with C++?

You can add the driver to your application to work with MongoDB using the C++11 or later standard. Download the library, mongocxx , from mongocxx.org or set up a runnable project by following our tutorial.

What is a MongoDB driver?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.


1 Answers

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)
like image 125
StuiterSlurf Avatar answered Oct 04 '22 10:10

StuiterSlurf