How to calculate time difference between two consecutive events in a collection

Hello,
Sensor sends packets in a 15-30 second interval which is stored in the mongodb collection.
For example
1-{18:56:23}
2-{18:56:56}
3-{18:57:23}
4-{18:57:45}
.
.
.

Now I have to do calculation for which I need to take out the difference between each such consecutive data packets time difference,
How can I find the difference between each consecutive packet time difference

Please provide sample documents in JSON format so that we can cut-n-paste directly into our system.

Please define how a packet is consecutive one or it is related to something else. For example, do you have packets from multiple devices in the same collection.

If this is a frequent use-case you might want to consider storing the time of the previous or next packet or the time interval permanently when you insert a new packet. Finding the time interval or the time of the previous / next packet will probably involve $lookup, so you either do it once at insertion time or every time you run the query.

Please close your redundant post How to calculate time difference between two consecutive events.

1 Like

Sorry for not making it more clear
the doc will look like

{
metadata:{
eventcode:100
}
power:on // this can be either on or off
time:1667984669//unix timestamp
timestamp: ISODate("2020-03-02T01:11:18.965Z")
}

Now the packets come every 15-30 sec, and I need the difference of every consecutive document timestamp for lets say 1 day.
For a day there will be 2000-3000 documents and I need time difference for every consecutive document, time difference calculated using timestamp

The plant has sensor, which sends data packets every 15-30 seconds, those packets are stored in a timeseries collection

A single document is not enough to let us experiment easily on your use-case. Especially when the use-case is about calculating value between 2 documents.

And we want real

If I cut-n-paste in mongosh the only document that you shared, I get

SyntaxError: Unexpected token, expected "," (5:0)

  3 | eventcode:100
  4 | }
> 5 | power:on // this can be either on or off
    | ^
  6 | time:1667984669//unix timestamp
  7 | timestamp: ISODate("2020-03-02T01:11:18.965Z")
  8 | }

And please

this way we do not have to look at 2 places to see if someone else provided a solution or not.