在数组mongoDB中搜索并返回对象

时间:2019-01-03 06:59:06

标签: mongodb laravel jenssegers-mongodb

我正在使用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"]

1 个答案:

答案 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_arrayforeach获得最终结果