Find the total time spent by an user in mongoDB

2020-02-07 06:08发布

问题:

I have a mongodb with the structure as below:

|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")

I need to find the total amount of time taken by an user in any particular location. I have read across multiple blogs and yet to find any concrete answer. I have the following:

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

回答1:

You can find the timeOfDay from the TimeOfVisit field and then use $sum to get the total count

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

You can further divide it to get the days, hours, minutes or seconds

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

For the mongodb 4.0 and above

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