【问题标题】:Profiling the MongoDB database to see the executed queries分析 MongoDB 数据库以查看执行的查询
【发布时间】:2012-12-16 13:38:14
【问题描述】:

有没有办法在 MongoDB 上查看已执行的查询?我使用以下命令在 Windows 上通过 mongo.exe 启用了分析:

db.setProfilingLevel(2);

这将启用分析,我可以使用以下命令查询配置文件数据:

db.system.profile.find().limit(10).sort( { ts : -1 } ).pretty()

但是,这并没有让我得到执行的查询。我知道我也可以使用IMongoQuery.ToJson() 方法来查看查询,但我正在使用带有 MongoDB C# 驱动程序的 Linq 查询(顺便说一句,我真的很想知道他们为什么调用这个 C# 驱动程序而不是 .NET 驱动程序)。

示例如下:

var people = db.GetCollection<Person>("People")
    .AsQueryable().Where(x => x.Sessions.Any(y => y.SessionDate != null));

var peeps = people.Select(x => 
    x.Sessions.Where(y => y.SessionDate != null)).ToList();

但是,能够执行以下操作真的很酷:

var people = db.GetCollection<Person>("People")
    .AsQueryable().Where(x => x.Sessions.Any(y => y.SessionDate != null))
    .Expression.ToJson();

但我猜这是不支持的。有什么想法吗?

【问题讨论】:

    标签: c# linq mongodb mongodb-.net-driver


    【解决方案1】:

    我认为没有IMongoQuery 就没有办法做到这一点。好消息是您可以将people 转换为MongoQueryable&lt;Person&gt; 并从那里获取IMongoQuery

    var people = db.GetCollection<Person>("People")
        .AsQueryable().Where(x => x.Sessions.Any(y => y.SessionDate != null));
    
    var mqPeople = (MongoQueryable<Person>)people;
    var query = mqPeople.GetMongoQuery().ToJson();
    

    编辑:

    看起来这仅适用于Where 子句。

    【讨论】:

    • 这看起来很对。感谢您提出这个问题。我会试一试,但我假设任何返回 IQueryable 的受支持的 Linq 方法都应该被视为 MongoQueryable&lt;T&gt;
    • 在大多数情况下这是一个有效的假设(对于Where 子句)。如果不是MongoQueryable&lt;T&gt;,那么很可能Linq 语句的一部分将在客户端而不是服务器上运行,这可能暗示您可以优化更多方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2017-04-06
    • 2012-10-28
    相关资源
    最近更新 更多