如何进行 OR 搜索
我想搜索部分名字和姓氏匹配 - 例如在 sql 中将
f_name LIKE J% OR l_name LIKE S%
匹配 John Smith 或 John Henry 或 Harry Smith 。
我假设我可能需要使用“$or”运算符,
到目前为止我相信它正在正确执行 LIKE % 部分,但我相信它正在执行“AND”搜索(意味着它搜索 f_name LIKE J % AND l_name LIKE S% 因此它只会匹配 John Smith):
$name1="J";
$name2="S";
$cursor = $this->clientCollection->find(array('f_name' => new MongoRegex('/^'.$name1.'/i'), 'l_name' => new MongoRegex('/^'.$name2.'/i') ));
注意:这将匹配包含,如 %J%
MongoRegex('/'.$name1.'/i')
这将匹配以(注意添加的 ^)开头,如 J%
MongoRegex('/^'.$name1.'/i')
I want to search for a partial first and last name match - for example in sql
f_name LIKE J% OR l_name LIKE S%
would match John Smith or John Henry or Harry Smith .
I am assuming I may need to use the "$or" operator,
I have this so far that I believe is doing the LIKE % part properly, but I believe it is doing an "AND" search (meaning it searches for f_name LIKE J% AND l_name LIKE S% so it would only match John Smith):
$name1="J";
$name2="S";
$cursor = $this->clientCollection->find(array('f_name' => new MongoRegex('/^'.$name1.'/i'), 'l_name' => new MongoRegex('/^'.$name2.'/i') ));
Note: This will match containing as in %J%
MongoRegex('/'.$name1.'/i')
This will match starts with (notice the added ^) as in J%
MongoRegex('/^'.$name1.'/i')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$or
接受一个子句数组,因此您基本上只需要在当前查询周围包装另一个数组:编辑:前面的示例错过了一组内部
array()
调用。我发布的原始错误示例如下所示:
这是一个有效的查询,但不是一个有用的查询。本质上,
f_name
和l_name
查询部分仍然是 AND 在一起,因此$or
部分是无用的(它只传递一个查询,所以它与单独运行该查询相同)。至于您在评论中提到的替代方案,该方案不起作用,因为查询中最外层的数组必须是关联数组。之所以会出现这种混乱,是因为 Mongo 的查询语法类似于 JSON,并且混合使用了对象和数组,但这两种结构在 PHP 中都由数组表示。 PHP Mongo 驱动程序基本上将 PHP 关联数组转换为 JSON 对象 (
{ ... }
),并将“普通”PHP 数组转换为 JSON 数组 ([ ... ]
) 。实际结果是,“普通”PHP 数组通常仅在关联数组内有效,例如为字段指定多个值时。 PHP Mongo 手册 中的以下示例显示了 "查询中的普通”数组:
$or
takes an array of clauses, so you basically just need to wrap another array around your current query:Edit: the previous example missed an inner set of
array()
calls.The original, wrong, example that I posted looked like this:
This is a valid query, but not a useful one. Essentially, the
f_name
andl_name
query parts are still ANDed together, so the$or
part is useless (it's only getting passed one query, so it's the same as just running that query by itself).As for the alternative you mentioned in your comment, that one doesn't work because the outermost array in a query has to be an associative array. The confusion arises because Mongo's query syntax is JSON-like and uses a mixture of objects and arrays, but both of those structures are represented in PHP by arrays. The PHP Mongo driver basically converts PHP associative arrays to JSON objects (
{ ... }
), and "normal" PHP arrays to JSON arrays ([ ... ]
).The practical upshot is that "normal" PHP arrays are generally only valid when inside an associative array, like when specifying multiple values for a field. The following example from the PHP Mongo manual shows a valid usage of a "normal" array in a query: