At this time, unlike count(), it appears that an explain() cannot be run on the countDocuments().
For example, I can successfully run an explain() on count(), as seen here:
PRIMARY> db.users.count({ "name" : "Robb Stark" })PRIMARY> db.users.count({ "name" : "Robb Stark" }) 1 PRIMARY> db.users.explain().count({ "name" : "Robb Stark" }) { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "sample_mflix.users", "indexFilterSet" : false, "parsedQuery" : { "name" : { "$eq" : "Robb Stark" } }, "queryHash" : "01AEE5EC", "planCacheKey" : "01AEE5EC", "winningPlan" : { "stage" : "COUNT", "inputStage" : { "stage" : "COLLSCAN", "filter" : { "name" : { "$eq" : "Robb Stark" } }, "direction" : "forward" } }, "rejectedPlans" : [ ] }...
However, if I try to run explain() on countDocuments(), it throws an error like this:
PRIMARY> db.users.countDocuments({ "name" : "Robb Stark" }) 1 PRIMARY> db.users.explain().countDocuments({ "name" : "Robb Stark" }) 2019-06-06T12:30:58.431-0700 E QUERY [js] TypeError: db.users.explain(...).countDocuments is not a function : @(shell):1:1
Now, I know that countDocuments() wraps the following aggregation operation and returns just the value of n:
db.collection.aggregate([ { $match: <query> }, { $group: { _id: null, n: { $sum: 1 } } } ])
Therefore, I tried to run explain() on the equivalent aggregation pipeline, which correctly yielded results.
PRIMARY> db.users.aggregate([ { $match: { "name" : "Robb Stark" } }, { $group: { _id: null, n: { $sum: 1 } } }])PRIMARY> db.users.aggregate([ { $match: { "name" : "Robb Stark" } }, { $group: { _id: null, n: { $sum: 1 } } }]) { "_id" : null, "n" : 1 } PRIMARY> db.users.explain().aggregate([ { $match: { "name" : "Robb Stark" } }, { $group: { _id: null, n: { $sum: 1 } } }]) { "stages" : [ { "$cursor" : { "query" : { "name" : "Robb Stark" }, "queryPlanner" : { "plannerVersion" : 1, "namespace" : "sample_mflix.users", "indexFilterSet" : false, "parsedQuery" : { "name" : { "$eq" : "Robb Stark" } }, "queryHash" : "01AEE5EC", "planCacheKey" : "01AEE5EC", "winningPlan" : { "stage" : "COLLSCAN", "filter" : { "name" : { "$eq" : "Robb Stark" } }, "direction" : "forward" }, "rejectedPlans" : [ ] } } }, { "$group" : { "_id" : { "$const" : null }, "n" : { "$sum" : { "$const" : 1 } } } } ]
So, it appears that there is something specific to countDocuments() that prevents explain() from being executed on it.