MongoDB中UTCDateTime结合$gte查询无结果问题求助
解决MongoDB按创建日期查询用户返回空数组的问题
我之前也碰到过一模一样的坑!你猜的没错,问题确实出在UTCDateTime的参数传递上——MongoDB的UTCDateTime要求传入毫秒级时间戳,但strtotime()返回的是秒级时间戳,直接传进去会导致时间匹配不上,自然查不到数据。
已验证的修复方案
你更新后的代码已经搞定了核心问题,关键就是把秒级时间戳乘以1000转成毫秒:
$date = '2018-05-02'; User::raw(function ($col) use($date) { return $col->aggregate([ ['$match' => [ 'created_at' => ['$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($date)*1000)] ]] ]); });
如果要精确匹配当天创建的用户,建议加上$lt限定到次日零点,避免包含次日的数据:
$startTimestamp = strtotime('2018-05-02') * 1000; $endTimestamp = strtotime('2018-05-03') * 1000; User::raw(function ($col) use($startTimestamp, $endTimestamp) { return $col->aggregate([ ['$match' => [ 'created_at' => [ '$gte' => new \MongoDB\BSON\UTCDateTime($startTimestamp), '$lt' => new \MongoDB\BSON\UTCDateTime($endTimestamp) ] ]] ]); });
扩展:实现一周前、昨天等时间区间查询
针对你提到的时间区间需求,用PHP的相对日期格式就能轻松实现,比手动拼接日期灵活多了:
1. 查询昨天创建的用户
$yesterdayStart = strtotime('yesterday 00:00:00') * 1000; $yesterdayEnd = strtotime('today 00:00:00') * 1000; User::raw(function ($col) use($yesterdayStart, $yesterdayEnd) { return $col->aggregate([ ['$match' => [ 'created_at' => [ '$gte' => new \MongoDB\BSON\UTCDateTime($yesterdayStart), '$lt' => new \MongoDB\BSON\UTCDateTime($yesterdayEnd) ] ]] ]); });
2. 查询最近7天(一周内)创建的用户
$oneWeekAgo = strtotime('-7 days') * 1000; $now = time() * 1000; User::raw(function ($col) use($oneWeekAgo, $now) { return $col->aggregate([ ['$match' => [ 'created_at' => [ '$gte' => new \MongoDB\BSON\UTCDateTime($oneWeekAgo), '$lt' => new \MongoDB\BSON\UTCDateTime($now) ] ]] ]); });
小提醒
- 始终记得给
UTCDateTime传毫秒级时间戳,这是最容易踩的坑! - PHP的相对日期格式(比如
yesterday、-7 days)非常实用,能减少手动计算日期的错误。
内容的提问来源于stack exchange,提问作者Kwame
相关产品推荐
相关产品推荐

