我试图获取与特定日期范围匹配的所有文档。我已经成功地在Mongo CLI中创建了查询,但是我在将其转换为PHP Mongo库时遇到了问题(我刚刚升级到PHP 7,因此使用新的驱动程序/库正在使用一些到)。
为什么我在CLI中取回结果,但我的代码中没有任何内容?
$search = [];
if (isset($_GET['days'])) {
$days = explode(',', $_GET['days']);
foreach ($days as $day) {
$date = $dates[$day];
$start = new DateTime($date, new DateTimeZone('America/New_York'));
$start = new MongoDB\BSON\UTCDateTime($start);
$end = new DateTime($date, new DateTimeZone('America/New_York'));
$end->add(DateInterval::createFromDateString('1 day'));
$end = new MongoDB\BSON\UTCDateTime($end);
$search[] = [
'date.start' => [
'$gte' => $start,
'$lte' => $end
]
];
}
}
$rEvents = $mongo->events->find($search);
$dates
将单词day翻译为与之对应的日期。当我检查创建的DateTime对象时,它们会更正,但仍然没有结果。我哪里出错?
答案 0 :(得分:0)
我工作了一段时间,直到找到了解决方法(它与php 7新的mongo驱动程序兼容)。
my db="TEST"
my collection="colUser"
所以我们开始吧。
1)首先,我们必须使驱动程序php无效,如下所示:
$database=new MongoDB\Driver\Manager;
// Instantiate the php 7 mongo library
//2)Prepare the date (mongo uses miliseconds from 1970 not seconds
//like php)
$date1="2015-01-02";
$date1=new DateTime($date1);
$date1=new MongoDB\BSON\UTCDatetime($date1->getTimeStamp() *
1000);//Transforming into miliseconds
$date2="2016-06-01";
$date2=new DateTime($date2);
$date2=new MongoDB\BSON\UTCDatetime($date2->getTimeStamp() * 1000);//
//Transforming second date into ms
//Prepare the array to select time from $date1 to $date2 from mongo db
$array=array("date"=>array(
"\$gte"=>$date1,
"\$lt"=>$date2 ));
$query=new MongoDB\Driver\Query($array);// Preparing the query
$rows=$database->executeQuery("TEST.colUser",$query);// Getting the data into
//object $rows
// NOW WHE HAVE TO PRINT THE DATE`s THAT WE FOUND IN THE INTERVAL FROM THE
//COLLECTIONS
foreach($rows as $k=>$v){// each object $v represents objects from one row
foreach($v as $key=>$value){// each object from one row
if($key=="date"){// "date" is the index time from collection
foreach($value as $t=>$time){// $value is an object and
//it needs an foreach "[milliseconds]->time"
$time=$time / 1000; //transform from ms into
//seconds
}
echo date("Y-m-d",(int)$time);//finally we are
//echoing the time in YEAR-MONTH-DAY
echo "<br>";
}
}
}