我有一些收藏:
$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());
我从mongo数据库中获取了一些数据(它正在运行):
$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));
我如何修改查询以获取按天分组的数据?
答案 0 :(得分: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 :(得分:1)
使用聚合和$ group运算符,如下所示:
$result = $collection->aggregate([
['$match' => ['date' => ['$gt' => $start, '$lt' => $end]]],
['$group' => ['_id' => ['date' => '$date']]]
]);
但它按纯日期分组。您可以使用$ dayOfMonth运算符按天进行分组:
['$group' => ['_id' => ['date' => ['$dayOfMonth' => '$date']]]]