我正在使用laravel-mongoDB 如何搜索景点和博客标题,而仅检索对象,而不是整个记录。 我尝试过
[
'$match' => [
"attraction.title" =>
['$regex' => '.*' . $request- >search . '.*']
],
],
结果是完整记录。 例如,如果搜索首先进行,则输出应为:
[{title: "first attraction", complete: false},{title: "first blog", complete: false}]
这是记录
[attraction: [{title: "first attraction", complete: false}, {title:"second attraction",
complete: true}]
blog: [{title: "first blog", complete: false}, {title: "second blog", complete: false}]
title: "test"
type: "internal"]
答案 0 :(得分:0)
我不是仅通过查询获得结果,而是希望对您有所帮助
$data = Model::raw(function ($collection) use ($request) {
return $collection->aggregate([
['$facet' =>
[
'attr' => [
[
'$match' => [
"attraction.title" => ['$regex' => '.*' . $request->search . '.*'],
],
],
[
'$unwind' => '$attraction'
],
[
'$project' => [
'title' => '$attraction.title',
]
],
[
'$match' => [
"title" => ['$regex' => '.*' . $request->search . '.*'],
],
]
],
'blog' => [
[
'$match' => [
"blog.title" => ['$regex' => '.*' . $request->search . '.*'],
],
],
[
'$unwind' => '$blog'
],
[
'$project' => [
'title' => '$blog.title',
]
],
[
'$match' => [
"title" => ['$regex' => '.*' . $request->search . '.*'],
],
]
]
]
],
]
);
});
$ data将类似于:
{
attr:[
{title:...},
{title:...}
],
blog:[
{title:...},
{title:...}
]
}
并使用iterator_to_array
和foreach
获得最终结果