首页 > 解决方案 > 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_dateandend_date不为空,我必须添加 3rd '$match'

我正在使用jenssegers/laravel-mongodb

需要建议:)

标签: mongodblaravelmongodb-queryjenssegers-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
    }
  },
  ....
]

推荐阅读