How do you explain a distinct query in MongoDB?
db.test3.distinct(\"id\", { key:\"value\"}).explain()
Errors with:
explain is
As of Mongo 3.2, you can do:
db.test3.explain().distinct("id", {key: "value"})
https://docs.mongodb.org/manual/reference/method/db.collection.explain/
You cannot use explain with the distinct as per this mongodb jira ticket. Instead you can use runCommand
and verify the stats,which is kinda similar to explain()
db.runCommand({ distinct: 'test3',key:'id',query:{key:"value"}})
In the above query test3 is collection name, key is a field name you want to apply distinct and finally if you wanted to specify any filters use query.
Check the samples
> db.runCommand({ distinct: 'items',key:'name',query:{offered:true}})
{
"values" : [
"test flat",
"Another aston martin",
"super luxury villa",
"Aston martin vanquish y for sale",
"Super car",
"Test item",
"another sports car",
"super car"
],
"stats" : {
"n" : 8,
"nscanned" : 10,
"nscannedObjects" : 10,
"timems" : 45,
"cursor" : "BasicCursor"
},
"ok" : 1
}
> db.runCommand({ distinct: 'items',key:'name',query:{offered:false}})
{
"values" : [
"yamaha",
"Test item"
],
"stats" : {
"n" : 2,
"nscanned" : 10,
"nscannedObjects" : 10,
"timems" : 0,
"cursor" : "BasicCursor"
},
"ok" : 1
}