sql >> Base de Datos >  >> NoSQL >> MongoDB

Encuentre el tiempo total empleado por un usuario en mongoDB

Puede encontrar el timeOfDay del TimeOfVisit campo y luego use $sum para obtener el recuento total

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

Puede dividirlo aún más para obtener los días, horas, minutos o segundos

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

Para mongodb 4.0 y superiores

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