MongoDB: Calculate dwell time between every status value change

后端 未结 3 1627
别跟我提以往
别跟我提以往 2020-11-29 14:12

I want to find out the dwell time between every presenceStatus change.

Example collection -

   /* 1 */

{
    \"_id\" : ObjectId(\"5e4889a7c7959f6a         


        
3条回答
  •  一个人的身影
    2020-11-29 14:56

    You could use a Map-Reduce on the collection, this will output the difference in seconds, but that should be relatively easy to change on your end.

    I haven't used this method on any sizeable collections, nor at all recently, so I'm not aware of performance implications by doing it in this fashion, please refer to the docs for more information.

    db.collection.mapReduce(
      function() {
        emit(0, this);
      },
      function(key,values){
        var state = values[0].presenceStatus;
        var stateTimestamp = values[0].updatedAt;
        var result = {
          changes: []
        };
    
        for (var i = 1; i < values.length; i++){
          var value = values[i];
          if (value.presenceStatus !== state) {
            if (state === 1) {
              result.changes.push({
                "dwellTime": value.updatedAt - stateTimestamp,
                "occupiedTime": value.updatedAt,
              });
            }
    
            state = value.presenceStatus;
            stateTimestamp = value.updatedAt;
          }
        }
    
        return result;
      },
      {
        out: { inline: 1 }
      }
    ).results[0].value.changes;
    
    [
            {
                    "dwellTime" : 26979,
                    "occupiedTime" : ISODate("2020-02-16T00:16:02.100Z")
            }
    ]
    

提交回复
热议问题