简体   繁体   English

如何在MongoDB的与众不同的命令中使用正则表达式?

[英]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. MongoDB独特的命令非常适合我要实现的目标,它可以为集合中的特定键获取一组唯一的结果。

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'? 我将如何构建此查询,使其仅返回与正则表达式“ chev”匹配的唯一值?

In php you can achieve this by doing 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"))
    )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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