在Mongo中减去日期
I am trying to substract two dates in MonoDB using the aggreation framework.
My code looks like this:
$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);
The problem is I'm getting an error that I am trying to substract 2 string.
Fatal error: Uncaught exception 'MongoResultException' with message 'localhost:27017: cant $subtract aString from a String
new ISODate
and the last_interacted_date
are both ISODate
objects.
My goal is to subtract a 'last_did_something' date from the date today, and return results for all queries that are within 2 days.
What am I doing wrong and how I can subtract dates?
我试图使用aggreation框架在MonoDB中减去两个日期。 p>
我的代码如下所示: p>
$ 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);
code> pre>
问题是我收到一个错误,我试图减去2个字符串。 p>
致命错误:未捕获异常'MongoResultException',消息为
'localhost:27017:cant $从字符串中删除aString p>
blockquote>
new ISODate code>和 last_interacted_date code>都是 ISODate code>对象。 p>
我的目标 strong>是从今天的日期中减去“last_did_something”日期,并返回2天内所有查询的结果。 p> \ n
我做错了什么以及如何减去日期? p>
div>
Since you want to query for documents that have the last_interacted_date
date field greater than or equal to the date two days ago, you need to create a new date object (2 days ago date) that you can use as your query comparison. The following demonstrates this:
$start = new MongoDate(strtotime( "-2 days"));
$ops = array(
array("$match" => array(
"last_interacted_date" => array("$gte" => $start)
)
)
);
$object -> aggregate($ops);
You can use a nifty library called Carbon that can help dealing with date/time in PHP much easier and more semantic so that your code can become more readable and maintainable:
// 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);