How do you explain a distinct query in MongoDB?

前端 未结 2 1016
别跟我提以往
别跟我提以往 2021-02-05 07:14

How do you explain a distinct query in MongoDB?

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

Errors with:

explain is          


        
2条回答
  •  暖寄归人
    2021-02-05 07:52

    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
    }
    

提交回复
热议问题