2016-04-29 60 views
0

我正在與laravel molequentmongoDb和我想寫一個查詢比較兩個日期之間的當前月份。 假設我有start_dateend_date,如果我在mysql中寫的查詢將是:個月具體查詢Mongodb和laravel

select * from table where month(curdate()) between month(start_date) and month(end_date) ; 

現在我必須寫這個查詢MongoDB中與laravel查詢生成器。

回答

0

您可能需要使用聚合框架來獲取結果。考慮運行在蒙戈外殼爲理念的示範如下管道,當然你需要有 實際領域,以取代虛擬字段:

var now = new Date(), 
    currentMonth = now.getMonth()+1, 
    pipeline = [ 
     { 
      "$project": { 
       "field1": 1, 
       "field2": 1, 
       "start_date": 1, 
       "end_date": 1, 
       "start_month": { "$month": "$start_date" }, 
       "end_month": { "$month": "$end_date" } 
      } 
     }, 
     { 
      "$match": { 
       "start_month": { "$lte": currentMonth }, 
       "end_month": { "$gte": currentMonth } 
      } 
     } 
    ]; 

db.collection.aggregate(pipeline); 

然後,您可以訪問底層的原始MongoDB的集合爲了使用聚合框架API:

$currentMonth = date("m"); 
$result = DB::collection('collectionName')->raw(function($collection) { 
    return $collection->aggregate(array(
     array(
      "$project"=> array(
       "field1" => 1, 
       "field2" => 1, 
       "start_date" => 1, 
       "end_date" => 1, 
       "start_month" => array("$month" => "$start_date"), 
       "end_month" => array("$month" => "$end_date") 
      ) 
     ), 
     array(
      "$match"=> array(
       "start_month" => array("$lte" => $currentMonth), 
       "end_month" => array("$gte" => $currentMonth) 
      ) 
     ) 
    )); 
});