2016-04-22 126 views
0

我想在MonoDB中使用聚合框架減去兩個日期。在蒙戈減去日期

我的代碼如下所示:

$ops = array(
    array('$project' => array("fieldMath" => 
    array('$subtract' => array('new ISODate()', 'new ISODate("last_interacted_date")')), 

    )), 
    array('$match' => array('fieldMath' => array('$gte' => 2), 
    ), 
    ), 
); 
$object -> aggregate($ops); 

的問題是我收到我想2。減去字符串錯誤。

Fatal error: Uncaught exception 'MongoResultException' with message 'localhost:27017: cant $subtract aString from a String

new ISODatelast_interacted_date都是ISODate對象。

我的目標是從今天的日期減去'last_did_something'日期,並返回2天內所有查詢的結果。

我在做什麼錯,我該如何減去日期?

+0

你可以準確地確定你想通過包括一些樣本文件和預期的輸出實現什麼? – chridam

+0

添加上面,基本上我想要所有的結果,其中當天扣除的日期大於2天。 –

+0

您應該計算查詢的「外部」日期。你只需要定期查詢,而不需要聚合。你當然這在PHP中。這不是JavaScript,而是BSON。所以你讓司機做翻譯。 –

回答

1

由於您想要查詢日期字段大於或等於兩天前的日期字段的文檔,您需要創建一個新的日期對象(2天前的日期),您可以將其用作查詢比較。下面演示了這一點:

$start = new MongoDate(strtotime("-2 days")); 
$ops = array(
    array("$match" => array(
     "last_interacted_date" => array("$gte" => $start) 
     ) 
    )  
); 
$object -> aggregate($ops); 

你可以用一記漂亮的圖書館叫做Carbon,可以幫助處理日期/時間在PHP更容易和更語義,使你的代碼可以變得更具可讀性和可維護性:

// get the current time 
$current = Carbon::now(); 

// subtract 2 days to the current time 
$start = $current->subDays(2); 

$ops = array(
    array("$match" => array(
     "last_interacted_date" => array("$gte" => $start) 
     ) 
    )  
); 
$object -> aggregate($ops); 
+0

你的答案几乎適用於我,但我需要天數,因爲我需要將它與另一個變量進行比較。 –