MongoDB日期范围查询在PHP中失效,提示非有效数值错误
解决PHP MongoDB驱动查询ISODate时的"非有效数值"错误
首先,你的问题出在混淆了旧版mongo扩展和新版mongodb扩展的日期处理类:你用的是最新的php_mongodb-1.3.4扩展(官方新版驱动),但代码里却用了旧版mongo扩展的mongoDate类——这个类在新驱动里根本不存在,而且即使强行使用,它的参数要求也和你传入的日期字符串不匹配,所以才会抛出A non well formed numeric value encountered的错误。
正确的解决方案:使用MongoDB\BSON\UTCDateTime类
新版mongodb扩展中,对应MongoDB里ISODate的类是MongoDB\BSON\UTCDateTime,它的构造参数要求是毫秒级的时间戳(不是日期字符串)。你有两种方式生成正确的实例:
方法1:直接将日期字符串转为毫秒时间戳
// 将日期字符串转为Unix时间戳(秒),再乘以1000得到毫秒 $startTimestamp = strtotime("2018-01-20T00:00:00Z") * 1000; $endTimestamp = strtotime("2018-01-25T00:00:00Z") * 1000; $document = $collection->find([ 'created_at' => [ '$gte' => new MongoDB\BSON\UTCDateTime($startTimestamp), '$lt' => new MongoDB\BSON\UTCDateTime($endTimestamp) ] ]);
方法2:用DateTime类处理(更清晰,支持复杂日期)
$startDate = new DateTime("2018-01-20T00:00:00Z"); $endDate = new DateTime("2018-01-25T00:00:00Z"); // 转成毫秒时间戳 $startTimestamp = $startDate->getTimestamp() * 1000; $endTimestamp = $endDate->getTimestamp() * 1000; $document = $collection->find([ 'created_at' => [ '$gte' => new MongoDB\BSON\UTCDateTime($startTimestamp), '$lt' => new MongoDB\BSON\UTCDateTime($endTimestamp) ] ]);
额外说明
- 如果你使用的是
mongodb/mongodbComposer库(基于官方扩展的上层封装),还可以直接传入DateTime对象,库会自动帮你转换为UTCDateTime:$document = $collection->find([ 'created_at' => [ '$gte' => new DateTime("2018-01-20T00:00:00Z"), '$lt' => new DateTime("2018-01-25T00:00:00Z") ] ]); - 确认你的PHP代码中已经正确引入了
MongoDB\BSON\UTCDateTime类(如果用的是命名空间环境),或者使用完整的类名。
内容的提问来源于stack exchange,提问作者codex
相关产品推荐
相关产品推荐

