簡體   English   中英

按日期分組以獲取一天、過去 7 天和一個月的點擊次數

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

[{'_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 天和一個月的點擊次數。 由於 model 是相同的,所以我想要基於lastAtmodelId計數。

我嘗試了聚合、分組功能。

這是純粹的 Mongo 方法,試試下面的代碼:

收藏:

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

Output:

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

注意:您可以輕松轉換為 PyMongo 語句,如果遇到困難,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM