MongoDB聚合+ $ match + $ group +条件过滤器

时间:2018-10-24 11:44:36

标签: mongodb laravel mongodb-query jenssegers-mongodb

这是我的代码:

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

其中第二个和第三个'$match'是可选的,基于过滤器。如果city_id不为空,则我必须添加第二个'$match';如果start_dateend_date不为空,则我必须添加第三个'$match'

我正在使用jenssegers/laravel-mongodb

需要建议:)

1 个答案:

答案 0 :(得分:1)

您可以使用$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
    }
  },
  ....
]