【问题标题】:Find the total time spent by an user in mongoDB查找用户在 mongoDB 中花费的总时间
【发布时间】:2019-05-26 01:24:12
【问题描述】:

我有一个结构如下的mongodb:

|User |Location  |TimeOfVisit
|U1.  |Cafeteria.|ISODate("2018-12-27T09:09:08.688Z")
|U2.  |Reception.|ISODate("2018-12-27T09:12:45.688Z")
|U1.  |Cafeteria.|ISODate("2018-12-27T09:45:38.688Z")
|U1.  |Cafeteria.|ISODate("2018-12-27T09:47:38.688Z")

我需要找出用户在任何特定位置所花费的总时间。我已经阅读了多个博客,但还没有找到任何具体的答案。我有以下内容:

aggregate([
        {
            "$match": {
                "User": {
                    "$eq": req.query.User
                }
            }
        },
        {
            "$group": {
                "_id": "$location",
                "totalMiniutes": {
                    <<Get the time>>
                }
            }
        }

【问题讨论】:

  • 你如何计算这样的持续时间?您不存储到达和离开的时间戳
  • 出发时间戳可以假设为表中的下一个timestamp。即|U2。 |Reception.|ISODate("2018-12-27T09:12:45.688Z") 可以是出发时间戳

标签: node.js mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您可以从TimeOfVisit 字段中找到timeOfDay,然后使用$sum 获取总数

db.collection.aggregate([
  { "$match": { "User": req.query.User }},
  { "$addFields": {
    "timeOfDay": {
      "$mod": [
        { "$toLong": "$TimeOfVisit" },
        1000*60*60*24
      ]
    }
  }},
  { "$group": {
    "_id": "$location",
    "totalTimeInMilliseconds": { "$sum": "$timeOfDay" }
  }}
])

Output

[
  {
    "_id": "Reception",
    "totalTimeInMilliseconds": 33165688
  },
  {
    "_id": "Cafeteria",
    "totalTimeInMilliseconds": 98846064
  }
]

你可以进一步划分得到天、小时、分钟或秒

1 hour = 60 minutes = 60 × 60 seconds = 3600 seconds = 3600 × 1000 milliseconds = 3,600,000 ms.

db.collection.aggregate([
  { "$addFields": {
    "timeOfDay": {
      "$mod": [
        { "$subtract": [ "$TimeOfVisit", Date(0) ] },
        1000 * 60 * 60 * 24
      ]
    }
  }},
  { "$group": {
    "_id": "$location",
    "totalTimeInMiniutes": {
      "$sum": { "$divide": ["$timeOfDay", 60 × 1000] }
    }
  }}
])

对于mongodb 4.0及以上

db.collection.aggregate([
  { "$addFields": {
    "timeOfDay": {
      "$mod": [
        { "$toLong": "$TimeOfVisit" },
        1000 * 60 * 60 * 24
      ]
    }
  }},
  { "$group": {
    "_id": "$location",
    "totalTimeInMiniutes": {
      "$sum": { "$divide": ["$timeOfDay", 60 × 1000] }
    }
  }}
])

【讨论】:

  • 但这给出了每个时间戳的分钟数,而不是每个区域花费的总时间,对吧?
  • OK 更新了答案。它会给你以毫秒为单位的总时间
  • 更新了答案。现在您将获得以分钟为单位的总时间
  • "无法识别的表达式 '$toLong'" mongo 3.x 版的任何替代方案?
猜你喜欢
  • 1970-01-01
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多