我想创建一个动态mongodb查询,如果条件为真,则插入其聚合的每个部分,否则不注入该部分。
例如,我想检查时间是否在凌晨1点到8点之间。如果是,则将定义的数组传递给mongodb查询,否则不传递任何内容。
if ($this->Not_in_1_8 == true) {
$this->N_IN_1_8 = array('dont_show_between_1_n_8' => array('$ne' => true));
}else {
$this->N_IN_1_8 = null;
}
$MidnightCheck = $this->N_IN_1_8;
$this->campaign = Bcamp::raw(function ($collection) use ($seat_category_list, $banner_size, $seat_filter_list, $gold_network, $MidnightCheck) {
return $collection->aggregate([
[
'$match' => [
'$and' => [
["targets.cats" => [
'$in' => $seat_category_list
]
],
['banners.' . $banner_size => [
'$exists' => true
]
],
['href' => [
'$nin' => $seat_filter_list
]
],
['targets.gold_network' => [
'$eq' => $gold_network
]
],
['status' => [
'$ne' => "Low_Budget"
]
],
['daily_budget_status' => [
'$ne' => "Low_Budget"
]
],
$MidnightCheck
]
]
],
[
'$project' => [
'ab' => [
'$cmp' => [
'$budget', '$click_cost'
]
]
]
],
[
'$match' => [
'ab' => [
'$lt' => 1
]
]
]
]);
});
但是在这个例子中它将在查询中注入null并使其出错并且我发现错误:bad query: BadValue: $or/$and/$nor entries need to be full objects
我已将其更改为$this->N_IN_1_8 = '';
仍未成功。
我需要一个中性变量或条件来传入,如果条件为false,则不会影响查询。 任何的想法?
仅供参考:我正在使用带有jenssegers / laravel-mongodb的Laravel 5.3框架 使用mongodb的包
答案 0 :(得分:1)
优先保持代码结构,即在条件代码中未使用预构建数组时,可以将$MidnightCheck
保留为null
并使用array_filter
包装数组:
return $collection->aggregate([
[
'$match' => [
'$and' => array_filter([
["targets.cats" => ['$in' => $seat_category_list]],
['banners.' . $banner_size => ['$exists' => true]],
['href' => ['$nin' => $seat_filter_list]],
['targets.gold_network' => ['$eq' => $gold_network]],
['status' => ['$ne' => "Low_Budget"]],
['daily_budget_status' => ['$ne' => "Low_Budget"]],
$MidnightCheck
])
]
// ...
在没有第二个参数的情况下调用array_filter
将过滤掉数组中的所有错误值,导致不需要的$MidnightCheck
消失。
我认为可能更清楚的是预先准备回调中的条件:
$conditions = [
["targets.cats" => ['$in' => $seat_category_list]],
['banners.' . $banner_size => ['$exists' => true]],
['href' => ['$nin' => $seat_filter_list]],
['targets.gold_network' => ['$eq' => $gold_network]],
['status' => ['$ne' => "Low_Budget"]],
['daily_budget_status' => ['$ne' => "Low_Budget"]],
];
if ($MidnighCheck) {
$conditions[] = $MidnightCheck;
}
return $collection->aggregate([
['$match' => [ '$and' => $conditions ],]
])