You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

MongoDB中使用UTCDateTime查找日期失败的技术求助

解决MongoDB\BSON\UTCDateTime查找失败的问题

你遇到的核心问题是MongoDB\BSON\UTCDateTime的构造函数参数用错了——它接受的是毫秒级的Unix时间戳,不是直接传入ISO格式的日期字符串。直接传字符串会导致构造出的UTCDateTime对象不符合预期,自然查不到对应数据。

下面给你几个正确的实现方式:

方法1:把日期字符串转成毫秒时间戳

先将ISO日期字符串转换成Unix时间戳(单位秒),再乘以1000得到毫秒数,传给UTCDateTime:

require '../vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");
$database = $client->db;
$center = $database->collection;

// 把ISO日期转成毫秒时间戳
$dateStr = "2018-03-22T09:03:07.147Z";
$timestampMs = strtotime($dateStr) * 1000;

// 正确构造UTCDateTime对象
$document = $center->find(["date" => new MongoDB\BSON\UTCDateTime($timestampMs)]);

方法2:用DateTime对象处理(更推荐,时区处理更准确)

如果需要考虑时区问题,用DateTime对象转换会更稳妥,能避免时区偏差:

require '../vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");
$database = $client->db;
$center = $database->collection;

$dateStr = "2018-03-22T09:03:07.147Z";
$dateTime = new DateTime($dateStr, new DateTimeZone('UTC'));
$timestampMs = $dateTime->getTimestamp() * 1000;

// 执行查找
$document = $center->find(["date" => new MongoDB\BSON\UTCDateTime($timestampMs)]);

额外提示:使用比较操作符(比如$gt/$gte)

既然你原本的需求是用$gt/$gte这类比较操作符筛选日期,这里给你举个实际例子,比如查找date晚于指定时间的文档:

// 构造要比较的目标时间点
$targetDate = new DateTime("2018-03-22T00:00:00Z", new DateTimeZone('UTC'));
$targetTimestampMs = $targetDate->getTimestamp() * 1000;

// 使用$gte执行范围查询
$documents = $center->find([
    "date" => ['$gte' => new MongoDB\BSON\UTCDateTime($targetTimestampMs)]
]);

最后要确认一点:你的集合里date字段必须已经是BSON日期类型(也就是存储时用了UTCDateTime,或者MongoDB自动识别的日期类型),如果之前存的是字符串,得先把字段类型转换成日期类型,才能用这种方式做准确的时间比较。

内容的提问来源于stack exchange,提问作者A. Morales

火山引擎 最新活动