'How to correctly perform join but with math operations in MongoDB?

Here I have a collection, say test, storing data with a field named timestamp (in ms). Documents in this collection are densely inserted with timestamp interval 60000. That's to say, I can always find one and only one document whose timestamp is 1 minute before that of a refered one (except for the very first one, of course). Now I want to perform a join to correlate each document with that whose timestamp is 1 minute before. I've tried this aggregation:

...
$lookup : {
  from: 'test',
  let : { lastTimestamp: '$timestamp'-60000 },
  pipeline : [
    {$match : {timestamp:'$timestamp'}}
  ],
  as: 'lastObjArr'
},
...

which intends to find the array of the very document and set it as the value of key lastObjArr. But in fact lastObjArr is always an empty one. What happend?



Solution 1:[1]

you defined a variable called "lastTimestamp" and you assign it with

'$timestamp'-60000 But you never use it, change your code as following it should work:

$lookup : {
  from: 'test',
  let : { lastTimestamp: '$timestamp'-60000 },
  pipeline : [
    {$match : {timestamp:'$$lastTimestamp'}}
  ],
  as: 'lastObjArr'
},

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jackandjac