0

我有一些收藏:

$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));

我如何需要修改我的查询以获取按天分组的数据?

4

2 回答 2

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);
于 2013-03-04T11:54:42.097 回答
1

使用聚合和 $group 运算符,如下所示:

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

但它按纯日期分组。您可以使用 $dayOfMonth 运算符按天分组:

['$group' => ['_id' => ['date' => ['$dayOfMonth' => '$date']]]]
于 2013-03-04T10:35:18.187 回答