MongoDb explain failed: “unknown top level operator: $query”

耗尽温柔 提交于 2019-12-23 15:25:52

问题


I'm trying to obtain explain from quite simple query. It uses posts collection with following schema:

> 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" : [ ]
}

Query I want to explain is this:

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

It produces proper result without any errors. But it throws the exception when I want to explain it. I've tried these commands to explain query:

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()

The error is always the same:

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
>

回答1:


From the 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()

So in your case, as the $explain operator has been deprecated since version 3.0, use the latter form of querying like:

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


来源:https://stackoverflow.com/questions/33595555/mongodb-explain-failed-unknown-top-level-operator-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!