doumeng2637 2016-04-22 06:54
浏览 640
已采纳

在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?

  • 写回答

1条回答 默认 最新

  • duancaishun4812 2016-04-22 07:25
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部