MongoDB C#驱动程序创建索引

时间:2018-07-09 14:47:14

标签: c# mongodb-.net-driver

我刚刚将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 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:1)

对于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 :(得分:0)

@StuiterSlurf可以帮助您使用更新的代码来更新此方法。


private void CreateExpiryAfterIndex(IMongoCollection<BsonDocument> collection)
{
    if (ExpireAfterSeconds <= 0) return;

    var indexKeys = Builders<BsonDocument>.IndexKeys;
    var options = new CreateIndexOptions{
                      Name = "expireAfterSecondsIndex",
                      ExpireAfter = new TimeSpan(ExpireAfterSeconds * TimeSpan.TicksPerSecond)
                  };

    if (collection != null)
    {        
       collection.Indexes.CreateOneAsync(keys: indexKeys.Ascending("timestamp"), options: options);

    }
}

我已将此问题发布在另一篇帖子中,该帖子被标记为要结束,并请我检查此问题

答案 3 :(得分:-1)

以下内容对我有用。

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