简体   繁体   中英

How to use regex with MongoDB's distinct command?

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'?

In php you can achieve this by doing

$cars = $db->command(
    array(
        "distinct" => "car_collection",
        "key" => "car_company.name",   // or what so ever key you wish to be distinct
        "query" => array("car_company.name" => new MongoRegex("/^chev/i"))
    )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM