查找用户在mongoDB中花费的总时间

时间:2018-12-28 06:56:24

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

我有一个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>>
                }
            }
        }

1 个答案:

答案 0 :(得分:2)

您可以从timeOfDay字段中找到TimeOfVisit,然后使用$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] }
    }
  }}
])