【问题标题】:How to use regex with MongoDB's distinct command?如何将正则表达式与 MongoDB 的不同命令一起使用?
【发布时间】:2026-01-15 13:40:01
【问题描述】:

MongoDB 的独特命令非常适合我想要实现的目标,即为集合中的特定键获取一组独特的结果。

我读过它支持正则表达式,但我不知道如何将它合并到查询中。

所以这个:

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

会回来

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

我将如何构建此查询以使其仅返回与“chev”等正则表达式匹配的唯一值?

【问题讨论】:

    标签: php regex json mongodb


    【解决方案1】:

    php 中,您可以这样做

    $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"))
        )
    );
    

    【讨论】:

    • 对不起,这不起作用。 Print_r($cars) 返回: Array ( [values] => Array ( ) [stats] => Array ( [n] => 0 [nscanned] => 5 [nscannedObjects] => 5 [timems] => 0 [cursor ] => BasicCursor ) [ok] => 1 )
    • 你能提供一些你试过的代码吗?其实我不使用php。我参考了文档并提供了我的解决方案。我关注了php.net/manual/en/class.mongoregex.phpphp.net/manual/en/mongodb.command.php