MongoDb 解释失败:"unknown top level operator: $query"

MongoDb explain failed: "unknown top level operator: $query"

我正在尝试从非常简单的查询中获取解释。它使用具有以下架构的帖子集合:

> db.posts.findOne()
{
        "_id" : ObjectId("55236e6182bf196454a952b6"),
        "Content" : "wuOfCjKborHcxkoyXzXiW",
        "CreatedAtUtc" : ISODate("2014-01-18T23:59:30.023Z"),
        "Tags" : [
                "sjM",
                "Van",
                "Orm"
        ],
        "Title" : "msAQAbQwAl",
        "Author" : "yIIhato",
        "Comments" : [ ]
}

我要解释的查询是这样的:

db.posts.find( { $query: {}, $orderby: { "CreatedAtUtc" : -1 } } )

它产生正确的结果,没有任何错误。但是当我想解释它时它会抛出异常。我试过这些命令来解释查询:

db.posts.explain().find( { $query: {}, $orderby: { "CreatedAtUtc" : -1 } } )
db.posts.find( { $query: {}, $orderby: { "CreatedAtUtc" : -1 } } ).explain()

var cursor = db.posts.find( { $query: {}, $orderby: { "CreatedAtUtc" : -1 } } )
cursor.explain()

错误总是一样的:

2015-11-08T16:20:40.137+0100 E QUERY    Error: explain failed: { "ok" : 0, "errm
sg" : "unknown top level operator: $query", "code" : 2 }
    at Error (<anonymous>)
    at Function.throwOrReturn (src/mongo/shell/explainable.js:34:19)
    at constructor.finish (src/mongo/shell/explain_query.js:188:36)
    at DBQuery.explain (src/mongo/shell/query.js:434:25)
    at (shell):1:8 at src/mongo/shell/explainable.js:34
>

来自docs:

Do not mix query forms. If you use the $query format, do not append cursor methods to the find(). To modify the query use the meta-query operators, such as $explain.

Therefore, the following two operations are equivalent:

db.collection.find( { $query: { age : 25 }, $explain: true } )
db.collection.find( { age : 25 } ).explain()

因此在您的情况下,由于 $explain 运算符自 3.0 版以来已被弃用,请使用后一种查询形式,如:

db.posts.find({}).sort({ "CreatedAtUtc" : -1 }).explain();