使用 MongoDatabase class 而不是 MongoDatabaseImpl

Using MongoDatabase class instead of MongoDatabaseImpl

我需要通过 Mongo C# 驱动程序设置分析级别。

Client.GetDatabase("test") returns IMongoDatabase 在运行时解析为 MongoDB.Driver.MongoDatabaseImpl 的接口。

根据 MongoDB .NET Driver API Documentation MongoDatase class 有一个 SetProfilingLevel 方法,我无法在运行时转换为该方法。

顺便说一句,我还安装了 Legacy Driver 2.0.1 版,因为 documentation 说里面有 SetProfilingLevel 方法。

此方法确实在旧版驱动程序中。所以首先安装旧版本,然后:

var client = new MongoServer(new MongoServerSettings());
var db = client.GetDatabase("db_name");
db.SetProfilingLevel(ProfilingLevel.All);

新 MongoDB 驱动程序(至少 2.3)没有更改分析级别的特定方法。
但是您可以使用 RunCommandAsync.

执行任何命令
public async Task SetProfilingLevelAsync(IMongoDatabase database, int level)
{
    var command = new BsonDocumentCommand<BsonDocument>(new BsonDocument("profile", level));
    await database.RunCommandAsync(command);
}