Reputation: 2996
I have some collection:
$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());
And I take some data from mongo database(it's working):
$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));
How I need modify my query to get data grouped by days?
Upvotes: 0
Views: 1394
Reputation: 36
$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);
Upvotes: 2
Reputation: 239
Use aggregation and $group operator, like this:
$result = $collection->aggregate([
['$match' => ['date' => ['$gt' => $start, '$lt' => $end]]],
['$group' => ['_id' => ['date' => '$date']]]
]);
But it groups by pure date. You can use $dayOfMonth operator for grouping by day:
['$group' => ['_id' => ['date' => ['$dayOfMonth' => '$date']]]]
Upvotes: 1