PHP mongo find field starts with

I'm trying to do the equivalent of a mysql like for php mongo; finding any link in my articles collection thats starts with www.foo.com/{category}. I can execute it fine in the shell but the php driver seems to not be interpolating my command correctly. And the mongo regex lacks thorough documentation. Heres my code.

$cats = ['news', 'life', 'humor'];

foreach($cats as $cat){
    $category = 'www.foo.com/' . $cat;
    $articles = db()->articles->find(['link' => array('$regex'=>new MongoRegex("/^$category/"))]);
}

it returns articles but the links do not match.


i tried concatenating the regex then passing it to the mongo query as opposed to regex'ing it within the query along with removing the quotes and that seemed to work. hope it helps someone else who has come across similar issues

$cats = ['news', 'life', 'humor'];

foreach($cats as $cat){
    $prefix = '/^'; 
    $suffix = '/'; // prefix and suffix make up the regex notation for text that starts with 
    $category = $prefix . 'www.foo.com/' . $cat . $suffix;
    $articles = db()->articles->find(['link' => array('$regex'=>new MongoRegex($category))]);
}
链接地址: http://www.djcxy.com/p/86396.html

上一篇: 检查一个字段是否包含字符串

下一篇: PHP mongo查找字段开头