问题
[{'_id': '5ebe39e41e1729d90de',
'modelId': '5ebe3536c289711579',
'lastAt': datetime.datetime(2020, 5, 15, 6, 42, 44, 79000),
'proId': '5ebe3536c2897115793dccfb',
'genId': '5ebe355ac2897115793dcd04'},
{'_id': '5ebe3a0d94fcb800fa474310',
'modelId': '5ebe3536c289711579',
'proId': '5ebe3536c2897115793d',
'genId': '5ebe355ac2897115793',
'lastAt': datetime.datetime(2020, 5, 15, 6, 43, 25, 105000)}]
I want to calculate count of hits for a day, for last 7 days and for a months. As the model is same, so I want the count of modelId
based on lastAt
.
I tried aggregate, group functions.
回答1:
This is pure Mongo approach, try the below code:
Collection:
[
{
"_id": "5ebe39e41e1729d90de",
"modelId": "5ebe3536c289711579",
"lastAt": ISODate("2020-05-13T06:42:44.000Z"),
"proId": "5ebe3536c2897115793dccfb",
"genId": "5ebe355ac2897115793dcd04"
},
{
"_id": "5ebe3a0d94fcb800fa474310",
"modelId": "5ebe3536c289711579",
"proId": "5ebe3536c2897115793d",
"genId": "5ebe355ac2897115793",
"lastAt": ISODate("2020-05-15T12:42:25.000Z")
},
{
"_id": "5ebe3a0d94474310",
"modelId": "5ebe3536c289711579",
"proId": "5ebe3536c2897115793d",
"genId": "5ebe355ac2897115793",
"lastAt": ISODate("2020-04-19T06:42:25.000Z")
}
]
Query:
var now = new Date()
var day1 = new Date(now - (1000 * 60 * 60 * 24 * 1))
var day7 = new Date(now - (1000 * 60 * 60 * 24 * 7))
var day30 = new Date(now - (1000 * 60 * 60 * 24 * 30))
db.test7.aggregate([
{
$group: {
_id: null,
day: {
$sum: {
$cond:[{$and: [{$gt: ['$lastAt', day1]},{$lte: ['$lastAt', now]}]}, 1, 0]
}
},
day7: {
$sum: {
$cond:[{$and: [{$gt: ['$lastAt', day7]},{$lte: ['$lastAt', day1]}]}, 1, 0]
}
},
day30: {
$sum: {
$cond:[{$and: [{$gt: ['$lastAt', day30]},{$lte: ['$lastAt', day7]}]}, 1, 0]
}
}
}
},
{
$project: {
_id:0
}
}
])
Output:
{ "day" : 1, "day7" : 1, "day30" : 1 }
Note: You can easily convert to PyMongo statements, if you get stuck, please let me know.
来源:https://stackoverflow.com/questions/61815812/group-by-date-to-get-count-of-hits-for-a-day-for-last-7-days-and-for-a-months