mongodb - MongoDB 聚合 + $match + $group + 条件过滤器
问题描述
这是我的代码:
$profiles = Profile::raw()->aggregate([
[
'$unwind' => '$channels'
],
[
'$match' => [
'channels.sign_up' => true,
]
],
[
'$match' => [
"city_id" => request()->input('city_id'),
]
],
[
'$match' => [
'created_at' => [
'$gte' => request('start_date', date('Y-m-d') . ' 00:00:00'),
'$lte' => request('end_date', date('Y-m-d') . ' 23:59:59'),
]
]
],
[
'$group' => [
'_id' => '$channels.slug',
'user_count' => ['$sum' => 1]
]
],
[
'$sort' => [
"user_count" => -1
]
]
]);
其中 2nd 和 3rd'$match'
基于过滤器是可选的。ifcity_id
不为空,我必须添加 2nd '$match'
,如果start_date
andend_date
不为空,我必须添加 3rd '$match'
。
我正在使用jenssegers/laravel-mongodb。
需要建议:)
解决方案
你可以使用$and
条件。
请检查以下对您有帮助的代码。
var matchConditionsArray = [];
matchConditionsArray.push({ 'channels.sign_up': true });
if (request.city_id) {
matchConditionsArray.push({ 'city_id': request.city_id });
}
if (request.start_date && request.end_date) {
matchConditionsArray.push({ "created_at": { $gte: request.start_date } }, { "created_at": { $lte: request.end_date } });
}
aggregate([
{
$match: {
$and: matchConditionsArray
}
},
....
]
推荐阅读
- python - 在两个类之间来回传递参数
- javascript - 用多个 else 和条件编写 if 的最简洁方法
- pytorch - PyTorch BatchNorm2d 计算
- angular - MatPaginator 和 MatTableDataSource - 更改总大小
- huawei-mobile-services - 为什么hms数据payload可以自动将jsonObject转为map
- node.js - 为什么我无法在客户端检索 cookie?
- python - seek() 函数在嵌套循环中不起作用
- java - RecyclerView 仅在添加更多项目时显示新项目
- javascript - React 中的动态值下拉列表
- docker - 为什么 Docker 构建以 SIGINT 结尾?