MongoDB C# 驱动程序创建索引

MongoDB C# Driver Create Index

我刚刚将 MongoDB 从版本 2.5.0 更新到 2.7.0。 Visual Studio 告诉我以下创建索引的方法已过时:

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

它建议我使用 CreateIndexModel

唯一的问题是我找不到一个例子来实现同样的效果。

我试过了:

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

但我得到以下异常:

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

以下对我有用。

public async Task CreateIndexOnCollection(IMongoCollection<BsonDocument> collection, string field)
{
    var keys = Builders<BsonDocument>.IndexKeys.Ascending(field);
    await collection.Indexes.CreateOneAsync(keys);
}

或者如果我们事先知道我们的索引是什么,我们可以像这样使用强类型实现:

public async Task CreateIndexOnNameField()
{
    var keys = Builders<User>.IndexKeys.Ascending(x => x.Name);
    await _usersCollection.Indexes.CreateOneAsync(keys);
}

MongoDB 2.7 驱动程序中的新方法是执行以下操作:

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)

对于带有索引选项的 BsonDocument,这里有一个类型不安全的方法:

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

// .NET Core
await collection.Indexes
                .CreateOneAsync(indexModel, cancellationToken: cancellationToken);