MongoDB php $in 和 $regex

2024-01-29

我正在尝试结合 $regex 和 $in 来进行简单的搜索。

例如我有一个这样的用户查询:

$user_query = "for focus red";

在我的每个文档的 mongodb 集合中,我都有一个关键字字段。我想获取字段关键字所在的文档:

{
    keywords :
        [0] => ford,
        [1] => focus,
        [2] => red
}

正如您所看到的,用户犯了一个错误,输入了“for”而不是“ford”。

我可以得到结果$in如果用户输入 Ford,但我不知道如何组合$regex and $in,我查看了 mongodb 文档和 php mongo 文档。


这是我的快速片段:

$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 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoDB php $in 和 $regex 的相关文章

随机推荐