web-dev-qa-db-ja.com

MongoDB C#ドライバー作成インデックス

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

4
StuiterSlurf

MongoDB 2.7ドライバーの新しい方法は、次のことです。

var notificationLogBuilder = Builders<NotificationLog>.IndexKeys;
var indexModel = new CreateIndexModel<NotificationLog>(notificationLogBuilder.Ascending(x => x.TimestampUtc));
await IMongoCollection.Indexes.CreateOneAsync(indexModel, cancellationToken: cancellationToken).ConfigureAwait(false);
18
StuiterSlurf

ここにインデックスオプションを持つ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);
await collection.Indexes.CreateOneAsync(indexModel, cancellationToken: cancellationToken).ConfigureAwait(false);
2
StuiterSlurf