doumeng2637 2016-04-22 14: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 15: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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题