PHP mongo查找字段始于 [英] PHP mongo find field starts with

查看:122
本文介绍了PHP mongo查找字段始于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做与php mongo类似的mysql.在我的文章集中找到链接以www.foo.com/{category}开头的任何链接.我可以在shell中很好地执行它,但是php驱动程序似乎无法正确插入我的命令.而且mongo regex缺乏详尽的文档.这是我的代码.

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.

推荐答案

我尝试连接正则表达式,然后将其传递给mongo查询,而不是在查询中将正则表达式与正则表达式一起删除引号,这似乎是可行的.希望它可以帮助遇到类似问题的其他人

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

这篇关于PHP mongo查找字段始于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆