你如何解释MongoDB中的独特查询?

时间:2011-12-08 11:03:07

标签: mongodb

如何解释MongoDB中的独特查询?

 db.test3.distinct("id", { key:"value"}).explain()

错误:

explain is not a function (shell)

2 个答案:

答案 0 :(得分:20)

从Mongo 3.2开始,你可以这样做:

db.test3.explain().distinct("id", {key: "value"})

https://docs.mongodb.org/manual/reference/method/db.collection.explain/

答案 1 :(得分:17)

根据此mongodb jira ticket,您无法使用与distinct不同的解释。相反,您可以使用runCommand并验证统计信息,这类似于explain()

 db.runCommand({ distinct: 'test3',key:'id',query:{key:"value"}})

在上面的查询中,test3是集合名称,key是要应用distinct的字段名称,最后如果要指定任何过滤器使用查询。

检查样本

> 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
}