问题描述
我有两个文档,想同时合并两个文档,并且想从合并表中获取数据.
I have two documents and want to join both bocuments and after I want to fetch the data from merged table.
例如,下面是主文档
{
"_id" : ObjectId("5d11bab64d51f58dbbd391lm"),
"title" : "Test test",
"test_url" : "https://www.example.com/",
}
这是详细信息文档
{
"_id" : ObjectId("5d1360536d94f726ec484426"),
"master_id" : ObjectId("5d11bab64d51f58dbbd391lm"),
"title" : "जेल में असलहा लहाराते हुए बदमाशों का वीडियो वायरल, गृह विभाग ने दी सफाई",
"description" : "जिला कारागार में अपराधियों द्वारा असलहा लहराते हुए वीडियो सामने आया है।िला कारागार में अपराधियों द्वारा असलहा लहराते हुए वीडियो सामने आया है।िला कारागार में अपराधियों द्वारा असलहा लहराते हुए वीडियो सामने आया है।"
}
两个文档都与主文档的 _id 和 master_id 链接.我想加入该表,并想在详细文档中添加标题.
both documents are linked with _id of master document and master_id.I want to join that table and want to add title in detail document.
,在结果之后,我想添加查询以从合并的文档中搜索数据.下面是搜索查询.
and after result I want to add query for search the data from merged document.below is the query for search.
$queryString = ".*".$queryString.".*";
$where = array(
'$or' => array(
array(
'title' => new \MongoDB\BSON\Regex($queryString),
),
array(
'description' => new \MongoDB\BSON\Regex($queryString),
),
)
);
推荐答案
您可以为此使用聚合管道
You can use aggregation pipeline for that
- 使用
$lookup
来加入两个集合 -
$unwind
从$lookup
阶段 生成的数组 -
$match
进行正则表达式搜索
- Use
$lookup
to join the two collections, $unwind
the resultant array from$lookup
stage$match
to do the regex search
如果还需要在master
文档的title
中进行regex
搜索,则可以将其添加到$match
阶段的$or
查询中,如果您不希望这样做,别忘了从$ or查询中删除(我已经添加了它).
If you need to do the regex
search on title
of master
document as well, you can add that to your $or
query of the $match
stage, and if you don't want that, don't forget to remove from the $or query (i have added it).
$pipeline = array(
array(
'$lookup' => array(
'from' => 'masters',
'localField' => '$master_id',
'foreignField' => '$_id',
'as' => 'master'
)
),
array(
'$unwind' => Array(
'path' => '$master',
'preserveNullAndEmptyArrays' => true
)
),
array(
'$match' => array(
'$or' => array(
array(
'title' => new \MongoDB\BSON\Regex($queryString),
),
array(
'description' => new \MongoDB\BSON\Regex($queryString),
),
array(
'master.title' => new \MongoDB\BSON\Regex($queryString),
),
)
)
),
array(
'$sort' => array(
'field_name' => 1
)
),
array(
'$limit' => 10
)
)
$results = $details->aggregate($pipeline);
现在,我的php并不是很好,我仍然设法为您编写了查询.请根据您的需要更改/修改代码.
Now, my php is not that great, still i have managed to write the query for you. Please change/modify the code according to your need.
问题是我给了您有关如何实现这一点的想法.希望有帮助.
The thing is i gave you the idea on how to acheive this. Hope that helps.
修改
对于sort
和limit
,请使用 $排序和 $ limit 流水线阶段,我已经添加了答案.
To sort
, and limit
, use $sort and $limit pipeline stages, I have added that in answer.
请不要忘记将field_name
替换为您要对结果进行排序的实际字段.
Dont forget to replace field_name
with the actual field you want to sort the result with.
这篇关于使用PHP的MongoDb Join查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!