27

How do you explain a distinct query in MongoDB?

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

Errors with:

explain is not a function (shell)

2 Answers 2

35

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/

Sign up to request clarification or add additional context in comments.

1 Comment

this one very simple and useful
18

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
}

2 Comments

I am not able to see the stats, I just get back values and ok as response.
I do not have the ability to mark it as an answer. I wonder why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.