我有一个名为adslog的集合,如下所示:
{
"_id" : ObjectId("5b06914115b903ae03435c3a"),
"id" : 24510236,
"serverId" : 23,
"timestamp" : ISODate("2018-05-16T15:02:17Z"),
"sessionid" : 0,
"ipAddress" : "10.1.11.250",
"remotePort" : 42049,
"op" : "view"
}
{
"_id" : ObjectId("5b06914115b903ae03435c3b"),
"id" : 24510249,
"serverId" : 23,
"timestamp" : ISODate("2018-05-16T15:02:19Z"),
"sessionid" : 0,
"ipAddress" : "10.1.11.250",
"remotePort" : 30886,
"op" : "click"
}
我写了这个Mongo查询来查找每天的观看次数:
db.adslog.aggregate([{"$match": {"op":"view"}},
{"$group":{"_id":{ "year": { "$year": "$timestamp" } , "month": { "$month": "$timestamp" }, "day": { "$dayOfMonth": "$timestamp" }},"count":{"$sum":1}}},
{"$sort":{"_id":1}} ])
我的结果如下:
[{'_id': {'year': 2018, 'month': 5, 'day': 16}, 'count': 57},
{'_id': {'year': 2018, 'month': 5, 'day': 17}, 'count': 142},
{'_id': {'year': 2018, 'month': 5, 'day': 18}, 'count': 3696},
{'_id': {'year': 2018, 'month': 5, 'day': 19}, 'count': 3814},
{'_id': {'year': 2018, 'month': 5, 'day': 20}, 'count': 388},
{'_id': {'year': 2018, 'month': 5, 'day': 21}, 'count': 236},
{'_id': {'year': 2018, 'month': 5, 'day': 22}, 'count': 172},
{'_id': {'year': 2018, 'month': 5, 'day': 23}, 'count': 521},
{'_id': {'year': 2018, 'month': 5, 'day': 24}, 'count': 27}]
现在,我一次只能获得一次视图或点击。
如果我想获得如下结果:
[{'_id': {'year': 2018, 'month': 5, 'day': 16}, 'count_views': 57, 'count_click': xxx}, and so on for all dates}]
应该如何做?
仅供参考,我也尝试使用db.adslog.aggregate([{"$match": {"op":"view"}}, {"$group":{"_id":{ "year": { "$year": "$timestamp" } , "month": { "$month": "$timestamp" }, "day": { "$dayOfMonth": "$timestamp" }},"count":{"$sum":"$op.view"}}}, {"$sort":{"_id":1}} ])
但是,它显示了我的错误,因为我不能在字符串值上使用sum。