在MySQL中,我会使用聚合函数来获取按日期分组的记录:
SELECT COUNT(id), DATE(created_at) creation FROM records GROUP BY creation;
+-----------+------------+
| COUNT(id) | creation |
+-----------+------------+
| 10 | 2015-04-22 |
+-----------+------------+
| 5 | 2015-11-22 |
+-----------+------------+
我可以在MongoDB中实现相同的功能,因为我还有一个id和created_at列:
db.contacts.find()
{ "_id" : ObjectId("55394a8c6d616386e3020000"), "name" : "sfdsf fddfgfdg", "email" : "gdfg@fdgij.com", "fax" : "", "birth_date" : null, "phone" : "453454564", "phone_2" : "", "updated_at" : ISODate("2015-04-23T19:39:56.966Z"), "created_at" : ISODate("2015-04-23T19:39:56.966Z") }
答案 0 :(得分:2)
使用$group
aggregation command汇总。要按日期而不是按日期时间进行分组,您可以使用运算符来提取year,month和day:
[
{
"$group" : {
"_id" : { month: { $month: "$date" },
day: { $dayOfMonth: "$date" },
year: { $year: "$date" } },
"count" : { $sum: 1 }
}
}
]
答案 1 :(得分:0)
您可以使用aggregation framework进行此操作。
db.contacts.aggregate([
{$group: {_id: "$created_at", count: {$sum: 1}}}
]);