按日期分组以获取一天,过去7天和一个月的点击数 [英] Group by date to get count of hits for a day, for last 7 days and for a months

查看:160
本文介绍了按日期分组以获取一天,过去7天和一个月的点击数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想计算一天,过去7天和一个月的点击数.由于模型相同,所以我希望基于lastAtmodelId计数.

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.

推荐答案

这是纯粹的Mongo方法,请尝试以下代码:

This is pure Mongo approach, try the below code:

收藏夹:

[
  {
    "_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")
  }
]

查询:

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
    }
  }
])

输出:

{ "day" : 1, "day7" : 1, "day30" : 1 }

注意::您可以轻松转换为PyMongo语句,如果遇到困难,请告诉我.

Note: You can easily convert to PyMongo statements, if you get stuck, please let me know.

这篇关于按日期分组以获取一天,过去7天和一个月的点击数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆