MongoDB PHP $ in和$ regex [英] MongoDB php $in and $regex
本文介绍了MongoDB PHP $ in和$ regex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将$ regex和$ in结合起来进行简单的搜索.
i'm trying to combine $regex and $in to do simple search.
例如,我有一个这样的用户查询:
For example I have a user query of this kind :
$user_query = "for focus red";
在我的mongodb集合中,对于每个文档,我都有一个关键字字段.我想获取文档,其中field关键字为:
In my mongodb collection for each document I have a keywords field. I want to get to get the document where the field keywords is :
{
keywords :
[0] => ford,
[1] => focus,
[2] => red
}
您可以看到用户输入了错误,并输入了"for"而不是"ford".
As you can see the user has done a mistake and typed "for" instead of "ford".
如果用户键入福特,我可以使用$in
获得结果,但是我不知道如何组合$regex
和$in
,我已经看过mongodb doc和php mongo doc.
I can get the results with $in
if the user types Ford, but I don't know how to combine $regex
and $in
, I have looked the mongodb doc and php mongo doc.
推荐答案
有我的快速摘要:
$user_query = preg_replace("/[[:blank:]]+/"," ", $user_query);
$arr_query = explode(' ', $user_query);
if (count($arr_query) > 1) {
$tmp = array();
foreach ($arr_query as $q) {
$tmp[] = new MongoRegex( "/". $q ."/" );
}
$who['keywords'] = array('$in' => $tmp);
} else {
$who['keywords'] = new MongoRegex( "/". $user_query ."/" );
}
$db->collection->find( $who );
这篇关于MongoDB PHP $ in和$ regex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文