MongoDB 聚合 + $匹配 + $组 + 条件过滤器

MongoDB aggregate + $match + $group + Condition filter

这是我的代码:

$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
                ]
            ]
        ]);

其中第 2 和第 3 '$match' 根据过滤器是可选的。如果 city_id 不为空则我必须添加第二个 '$match' 如果 start_dateend_date 不为空则我必须添加第三个 '$match'.

我正在使用 jenssegers/laravel-mongodb

需要建议:)

您可以使用 $and 条件。

Please check below code that help you.

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
    }
  },
  ....
]