Group by date to get count of hits for a day, for last 7 days and for a months

北战南征 提交于 2020-06-17 14:03:40

问题


[{'_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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!