MongoDB C#驱动程序创建索引 [英] MongoDB C# Driver Create Index

查看:958
本文介绍了MongoDB C#驱动程序创建索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

建议我使用 CreateIndexModel .

唯一的问题是,我找不到能使它正常工作的示例.

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

我尝试过:

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

推荐答案

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

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));
await IMongoCollection.Indexes.CreateOneAsync(indexModel, cancellationToken: cancellationToken).ConfigureAwait(false);

这篇关于MongoDB C#驱动程序创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆