我正在尝试使用aggreation框架在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 个字符串。
致命错误:未捕获的异常"MongoResultException",并显示消息 'localhost:27017:无法从字符串$subtract
字符串
new ISODate
和last_interacted_date
都是ISODate
对象。
我的目标是从今天的日期中减去一个"last_did_something"日期,并返回 2 天内所有查询的结果。
我做错了什么,我如何减去日期?
由于要查询 last_interacted_date
日期字段大于或等于两天前日期的文档,因此需要创建一个新的 date 对象(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);