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

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮