Find the total time spent by an user in mongoDB

后端 未结 1 2052
野趣味
野趣味 2020-12-12 02:05

I have a mongodb with the structure as below:

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


        
相关标签:
1条回答
  • 2020-12-12 02:53

    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] }
        }
      }}
    ])
    
    0 讨论(0)
提交回复
热议问题