2017-02-09 146 views
2

我试图执行一个MongoDB 聚合使用PHP查询。MongoDB聚合与PHP

基本上,我得到了波纹管查询,并将其使用MongoDB的shell时没有问题,执行:

db.getCollection('frete').aggregate([ 
    {$match : { 
     '$and': [ 
      { 'data_UTC': {$gte: ISODate('2017-01-20T00:00:00-02:00'), $lt: ISODate('2017-01-29T00:00:00-02:00') } }, 
      { 'carga': { $regex : new RegExp('soja', "i") }} 
     ] 
    } 
    }, 
    {$group : {_id: { $dateToString: { format: "%Y-%m-%d", date: { $subtract: ['$data_UTC', 1000 * 60 * 60 * 2] } } }, qtd_acessos: {$sum:1} }}, 
    { $sort: { _id: -1 } }, 
    { $limit: 50} 
]) 

然而,当我试图通过PHP执行相同的查询(我composer.json使用"mongodb/mongodb": "^1.0.0"依赖)在调用MongoDB PHP's aggregate()方法后,没有任何响应返回:

有人可以帮我翻译上面的查询到它的PHP等价物吗?我有以下,但也许我错过了一些东西:

$start = new \MongoDB\BSON\UTCDateTime(strtotime('2017-01-20T00:00:00-02:00')); 
$end = new \MongoDB\BSON\UTCDateTime(strtotime('2017-01-29T00:00:00-02:00')); 
$regex = new \MongoDB\BSON\Regex('soja', 'i'); 

$filter = [ 
    ['$match' => [ 
      '$and' => [ 
       ['data_UTC' => ['$gte' => $start, '$lt' => $end]], 
       ['carga' => ['$regex' => $regex]] 
      ] 
     ] 
    ], 
    ['$group' => ['_id' => ['$dateToString' => ['format' => "%Y-%m-%d", 'date' => ['$subtract' => ['$data_UTC', 1000 * 60 * 60 * 2]]]], 'qtd_acessos' => ['$sum' => 1]]], 
    ['$sort' => ['_id' => -1]], 
    ['$limit' => 50] 
]; 

谢谢!

回答

0

strtotime返回自1970年1月1日00:00:00以来的秒数。

乘以1000将其转化为毫秒。

这应该得到你所需要的。

$start = new \MongoDB\BSON\UTCDateTime(strtotime('2017-01-20T00:00:00-02:00') * 1000); 
$end = new \MongoDB\BSON\UTCDateTime(strtotime('2017-01-29T00:00:00-02:00') * 1000); 

小心日间照明当调整偏移时节省(如果适用)。不要手动做。如果可能的话,用偏移量保存日期。

0

用mongodb标准库检查将适用于你。

$pipeline = array(
        array('$match' => 
            array('$and' => 
              array( array('data_UTC' => array('$gte' => new MongoDate(strtotime('2017-01-20T00:00:00-02:00')), $lt: new MongoDate(strtotime('2017-01-20T00:00:00-02:00')))), 
                array('carga' => array($regex => new MongoRegex("/soja$/i"))) 
               ) 
             ) 
         ), 
        array('$group' => array ('_id' => array('$dateToString' => array('format' => "%Y-%m-%d", 'date' => array('$subtract' => array('$data_UTC', 1000 * 60 * 60 * 2)))), 
                'qtd_acessos' => array('$sum' => 1)), 
             array('$sort' => array(_id => -1)), 
             array('$limit' => 50) 
         ) 
       ) 

    $this->mongodb->aggregate($pipeline, 'db_collection_name');