2013-03-04 34 views
0

我有一些收藏:如何在MongoDB + PHP中將數據按天分組?

$data_to_insert = array('date'=> $current_date, 'str_date' => $today_date_str, 'user_id' => intval($post->post_author), 'post_id' => $post->ID, 'user_ip' => current_user_ip()); 

我需要一些數據從數據庫蒙哥(它的工作):

$start = new MongoDate(strtotime("-14 days")); 
$end = new MongoDate(strtotime(date("Y-m-d H:i:s"))); 

$last_day_query = $hits_collection->find(array("date" => array('$gt' => $start, '$lte' => $end), "user_id" => $current_user->ID)); 

如何,我需要修改我的查詢得到的數據按天分組?

回答

2
$ops = array(
       array(
         '$match' => array(
              'user_id' => $current_user->ID, 
              'date' => array(
                  '$gt' => $start, 
                  '$lte' => $end 
                  ) 
             ), 
        ), 
       array(
         '$project' =>array(
              'date' => 1, 
              'user_id' => 1 
              ), 
         '$group' => array('_id' => '$str_date', 'views' => array('$sum' => 1)), 
       ), 

    ); 

    $result = $hits_collection->aggregate($ops); 
+1

不知道爲什麼這有兩種選票,他甚至沒有解釋他在做什麼。此外,這僅適用於假設'str_date'是一天而且也不需要'$ project'的情況,事實上,由於文檔從項目傳遞到組的方式,此聚合不起作用。 – Sammaye 2013-03-04 13:42:30

+1

它真的工作:)在str_date我有「2013-03-03」類似的數據。 – inlanger 2013-03-04 14:21:28

1

使用聚合和$組操作員,像這樣:

$result = $collection->aggregate([ 
    ['$match' => ['date' => ['$gt' => $start, '$lt' => $end]]], 
    ['$group' => ['_id' => ['date' => '$date']]] 
]); 

但團體純日期。您可以使用$請將dayOfMonth運營商按天分組:

['$group' => ['_id' => ['date' => ['$dayOfMonth' => '$date']]]]