[英]Find MongoDB data with PHP
Mongodb search with PHP code: 使用PHP代码进行Mongodb搜索:
$cond=array();
$cond=array_merge($cond,array("clicks" => array('$gt' =>6)));
if (isset($lang)){
$cond=array_merge($cond,array("$or" => array(array("lang" =>'de'),array("lang" =>'fr'))));
}
if (isset($country)){
$cond=array_merge($cond,array("$or" => array(array("country" =>'us'),array("country" =>'uk'))));
}
Problem: On the last line, the second $or
of country is replacing the first $or
of lang. 问题:在最后一行,国家的第二个
$or
替换了lang的第一个$or
。 Would be great if anyone can suggest how can we avoid this overriding issue? 如果有人可以建议我们如何避免这个压倒性的问题,那就太好了吗?
Actually I'm new to MongoDB, I want to create a find query in MongoDB. 实际上,我是MongoDB的新手,我想在MongoDB中创建一个查找查询。 I have to build the query on the basis of some condition flags (eg if '$country=true' only then embed country filter) for each column.
我必须根据每列的某些条件标志(例如,如果仅'$ country = true'然后嵌入国家/地区过滤器)来构建查询。 Similar to SQL The output I need is:
与SQL类似,我需要的输出是:
"Where clicks > 6 and (lang = 'de' or lang = 'fr') and (country = 'us' or country = 'uk')" “点击次数> 6,并且(lang ='de'或lang ='fr')和(country ='us'或country ='uk')”
This is how your resulting array should look like: 这就是结果数组的样子:
$cond = [
'$and' => [
['clicks' => [ '$gt' => 6 ]],
['$or' => [
[ 'lang' => 'de' ],
[ 'lang' => 'fr' ]
]],
['$or' => [
[ 'country' => 'us' ],
[ 'lang' => 'uk' ]
]]
]
];
Now, to achieve this by using the modular approach you have specified, you could do something like this: 现在,要使用指定的模块化方法来实现此目的,可以执行以下操作:
$cond = [
'$and' => [
['clicks' => [ '$gt' => 6 ]]
]
];
if (isset($lang)) {
$cond['$and'][] = ['$or' => [['lang' =>'de'], ['lang' =>'fr']]];
}
if (isset($country)) {
$cond['$and'][] = ['$or' => [['country' =>'us'], ['country' =>'uk']]];
}
Hopefully this will demonstrate the way to assemble nested or/and query in PHP, so you can adjust it further as your design will demand. 希望这将演示在PHP中组装嵌套或/和查询的方法,因此您可以根据设计需要进一步调整它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.