有个需求是要统计mongodb的数据,按日期查询
如下图,按月查询
db.getCollection('ch_diet').aggregate([
{
"$match": {
"CH_create_time": {"$gt": ISODate("2018-12-31T16:00:00.000Z"), "$lt": ISODate("2019-12-31T16:00:00.000Z")},
"CH_comment": {"$exists": true},
"CH_comment.CH_description": {$ne: ""}
}
},
{
"$project": {
// 处理时区,因为mongo存储的是UTC时间,加8时区
day: {$dayOfMonth: {date: "$CH_m_date", timezone: "+08"}},
}
},
{
"$group": {
_id: "$day",
sum: {$sum: 1},
}
},
{
"$sort": {
"_id": 1
}
}
])
还有这种情况,统计出总数来,还要统计人数多少,就是要根据人的id去重,需要group两次
参考了这篇文章:https://blog.csdn.net/lff0305/article/details/50034735
db.getCollection('ch_glucose').aggregate([
{
"$match": {
"CH_m_date": {"$gt": ISODate("2020-01-31T16:00:00.000Z"), "$lt": ISODate("2020-02-10T16:00:00.000Z")}
}
},
{
"$group": {_id: {"date": {$dayOfMonth: {date: "$CH_m_date", timezone: "+08"}}, "user":"$CH_user_id"}}
},
{
"$group": {_id: {"date": "$_id.date"}, count: {$sum: 1}}
},
{
"$sort": {
"_id": 1
}
}
])