dsf4354353452 2018-01-14 18:26
浏览 82

MongoDB PHP驱动程序:日期搜索不起作用

I am migrating to PHPLIB from the old MongoDB driver. Unfortunately, I am running into issues attempting to convert date searches. I am trying to retrieve documents that were added to the database from a certain date (yesterday), however, when I perform a search, I'm getting back the count for all the records regardless of the value in 'added_on'. Not sure what I'm doing wrong.

    $collection = $mongo->getCollection("records");
$yesterday = new DateTime(date('Y-m-d').' 00:00:00');
$dateFrom = new MongoDB\BSON\UTCDateTime($yesterday->format('U'));
    $response = $collection->count(['added_on' => ['$gte' => $dateFrom], 'instance' => $element, 'invisible' => false]);

var_dump of UTCDateTime shows a valid value:

object(MongoDB\BSON\UTCDateTime)#477 (1) { ["milliseconds"]=>
string(10) "1515954053" }

Example of a document expected to return:

{ "_id" : ObjectId("5a5badcffe23a278e2bb739a"), "instance" : ObjectId("591555806803fa06650b474c"), "added_on" : ISODate("2018-01-14T23:25:55Z"), "invisible" : false, "reviewed" : true }

Any help would be appreciated.

UPDATE: Removing the variable that is sent to the UTCDateTime object like this:

$dateFrom = new MongoDB\BSON\UTCDateTime();

works (as can be seen above I've added one record in the future). Problem is when I send the variable to specify the timestamp that I need.

  • 写回答

1条回答 默认 最新

  • drblhw5731 2018-01-14 20:34
    关注

    Was able to find the issue - this behavior is caused when MongoDB\BSON\UTCDateTime receives a value generated by strtotime. The value appears to be valid (no errors are generated), but because it represents and not milliseconds, it does not behave as expected.

    I've added the following function to a custom MongoDB class I'm using:

    public function date($timestamp) {
        $timestamp = strtotime($timestamp) * 1000;
        $object = new MongoDB\BSON\UTCDateTime($timestamp);
        return $object;
    }
    

    Then I just call:

    $response = $collection->count(['added_on' => ['$lt' => $mongo->date($yesterday->format('Y-m-d H:i:s'))], 'instance' => $element, 'invisible' => false]);
    

    $mongo being the object of the custom class.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度