Stu*_*urf 4 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));
Run Code Online (Sandbox Code Playgroud)
已经过时了.他们希望我们使用CreateIndexModel https://mongodb.github.io/mongo-csharp-driver/2.6/apidocs/html/T_MongoDB_Driver_CreateIndexModel_1.htm
唯一的问题是我找不到一个能够实现同样功能的例子.
我试过了:
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);
}
Run Code Online (Sandbox Code Playgroud)
我一直得到以下异常:
System.FormatException: 'JSON reader was expecting a value but found 'TimestampUtc'.'
Stu*_*urf 17
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);
Run Code Online (Sandbox Code Playgroud)
对于带有索引选项的 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7012 次 |
| 最近记录: |