我在mongo db上遇到一个问题,即使用“ $ group”中的group by grouping函数在日期上获取记录为“创建”,但是在表mongoDb数据库中有datetime格式。
当我运行mongo查询时,出现错误“无法从BSON类型的字符串转换为日期”
$date = date('Y-m-d',strtotime(-1 month));
$users = $this->common_model->aggregate($this->database['USER_DATA'], array(array('$match' => array('created' => array('$gte' => $date))),
array('$sort' => array('_id.created' => -1)),
array('$group' => array('_id' => array('year' => array('$year' => '$created'), 'month' => array('$month' => '$created'), 'day' => array('$dayOfMonth' => '$created')), 'count' => array('$sum' => 1))),
));
在使用
之前array('$group' => array('_id' => array('created' => '$created')), 'count' => array('$sum' => 1)),
它正在工作,但是没有按组按日期记录所需的记录,因为在表中我们有日期时间。
答案 0 :(得分:0)
您可以这样尝试:
$users = $this->common_model->aggregate($this->database['USER'], array(
array('$match' => array('created' => array('$gte' => $date))),
array('$sort' => array('_id.created' => -1)),
array('$project' => array('_id' => 0, 'y' => array('$year' => ISODate('$created') . getFullYear()), 'm' => array('$month' => ISODate('$created') . getMonth() + 1), 'd' => array('$dayOfMonth' => ISODate('$created') . getDate()))),
array('$group' => array('_id' => array("year" => '$y', "month" => '$m', "day" => '$d'), 'count' => array('$sum' => 1))),
));