Tuesday, April 11, 2017

MongoDB Raw query to select documents which are in given datetime period

I want to select documents which are in user given date time period like between :

$from_date : "2017-01-07 09:08:59" To `$to_date : "2017-08-09 09:08:59"` 

I'm using laravel framework and jenssegers/laravel-mongodb mongodb driver to run my query, And this is my Raw query :

 $normal_banners = BannerView::raw(function ($collection) use ($id, $from_date, $to_date) {
      $conditions = [
         ["camp_id" => ['$eq' => $id]],
         ['$or' => [
              ['seat_target_status' => ['$eq' => true]],
              ['seat_target_status' => ['$eq' => false]]
         ]],
         ['camp_target_status' => ['$eq' => false]],
         ];

         if ($to_date) {
            $conditions[] = ['updated_at' => ['$lte' => $to_date]];
         }

         if ($from_date) {
            $conditions[] = ['created_at' => ['$gte' => $from_date]];
         }

         return $collection->aggregate([
            ['$match' => ['$and' => $conditions]],
         ]);
    })->count();

But my problem is that it returns 0 as result; while there are 16 documents in this time period.

I've tried this method to get the count of them but still 0 result :

$targeted_banners = BannerView::Where('camp_id', $id)
  ->where('seat_target_status', true)
  ->orwhere('seat_target_status', false)
  ->where('camp_target_status', false)
  ->whereBetween("created_at", array($from_date, $to_date))
  ->count();

Any suggestion how to fix this ?



via Mohammad_Hosseini

Advertisement