1
votes

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.

1

1 Answers

1
votes

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))]);
}