Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
>
like image 781
Arkadiusz Kałkus Avatar asked Nov 08 '15 15:11

Arkadiusz Kałkus


1 Answers

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();
like image 66
chridam Avatar answered Nov 10 '22 07:11

chridam