我是MongoDB的新手,正在用PHP编写脚本,并且我正在使用MongoDB来存储信息。目前,我正在处理搜索结果,需要查询以获取结果,如果某些字符匹配,则获取所有相关数据。
当前,我正在使用以下脚本
$queryString = ".*".$queryString."*";
$where = array(
'$or' => array(
array(
'title' => new \MongoDB\BSON\Regex($queryString),
),
array(
'description' => new \MongoDB\BSON\Regex($queryString),
),
)
);
这工作正常,但仍然跳过了一些单词。请让我知道获取确切信息的最佳方法是什么。
例如:
{
"_id" : ObjectId("5d1360536d94f726ec484426"),
"master_id" : ObjectId("5d11bab64d51f58dbbd391bf"),
"title" : "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).",
"description" : "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
"pub_date" : "\n\t Wed, 26 Jun 2019 13:30:18 GMT\t",
"created_on" : "2019-06-26 17:38:51",
"modified_on" : "2019-07-10 09:34:33"
}
如果我们搜索字符为“ Lor” 的数据,则所有在集合中(例如Lorem)找到包含单词“ Lor” 的单词的情况下,所有结果应为返回。
这与LIKE
中的mysql
查询相同。
答案 0 :(得分:1)
您可以使用不区分大小写的正则表达式搜索
尝试一下:
$queryString = ".*".$queryString.".*";
$where = array(
'$or' => array(
array(
'title' => array (
'$regex' => new \MongoDB\BSON\Regex($queryString),
'$options' => 'i'
)
),
array(
'description' => array (
'$regex' => new \MongoDB\BSON\Regex($queryString),
'$options' => 'i'
)
),
)
);