代码之家  ›  专栏  ›  技术社区  ›  StuiterSlurf Marius

MongoDB C驱动程序创建索引

  •  2
  • StuiterSlurf Marius  · 技术社区  · 6 年前

    我刚把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'.'

    2 回复  |  直到 6 年前
        1
  •  13
  •   StuiterSlurf Marius    6 年前

    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);
    
        2
  •  -1
  •   petey m    6 年前

    以下是我的工作。

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