Home:ALL Converter>How to use regex with MongoDB's distinct command?

How to use regex with MongoDB's distinct command?

Ask Time:2013-01-06T21:39:56         Author:styke

Json Formatter

MongoDB's distinct command is perfect for what I'm trying to achieve, which is get a unique set of results for a particular key in a collection.

I've read that it supports regex, but I can't work out how to incorporate it into the query.

So this:

db.runCommand({distinct:'cars',key:'car_company.name'})

Would return

{
    "values" : [
        "Chevy",
        "Porche",
        "Chevrolet",
        "BMW",
        "Mercedes-Benz",
    ],
    "stats" : {
        "n" : 5,
        "nscanned" : 5,
        "nscannedObjects" : 5,
        "timems" : 0,
        "cursor" : "BasicCursor"
    },
    "ok" : 1
}

How would I build this query so that it only returns the unique values that match a regex of say, 'chev'?

Author:styke,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/14182673/how-to-use-regex-with-mongodbs-distinct-command
yy