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

Landeeyo picture Landeeyo · Nov 8, 2015 · Viewed 17.4k times · Source

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
>

Answer

chridam picture chridam · Nov 8, 2015

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