如何在 MongoDB 中正确执行连接但使用数学运算?
How to correctly perform join but with math operations in MongoDB?
这里我有一个集合,比如说 test
,存储数据的字段名为 timestamp
(以毫秒为单位)。该集合中的文档以timestamp
间隔60000密集插入。也就是说,我总是可以找到一个并且只有一个文档其timestamp
比引用的文档早1分钟(除了第一个一,当然)。现在我想执行连接以将每个文档与 1 分钟前 timestamp
的文档相关联。我试过这种聚合:
...
$lookup : {
from: 'test',
let : { lastTimestamp: '$timestamp'-60000 },
pipeline : [
{$match : {timestamp:'$timestamp'}}
],
as: 'lastObjArr'
},
...
它打算找到文档的数组并将其设置为键lastObjArr
的值。但实际上 lastObjArr
始终是空的。发生什么事了?
您定义了一个名为“lastTimestamp”的变量并将其分配给
'$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'
},
您的 $lookup
管道不完整,因为它缺少必要的数学运算符。首先,由于多种因素,lastObjArr
为空,其中之一是表达式
let : { lastTimestamp: '$timestamp'-60000 },
计算不正确,需要使用$subtract
运算符
let : { lastTimestamp: { $subtract: ['$timestamp', 60000] } },
此外,$match
管道步骤需要使用 $expr
operator together with $eq
才能使查询正常工作,即
$lookup : {
from: 'test',
let : { lastTimestamp: { $subtract: ['$timestamp', 60000] } },
pipeline : [
{ $match : {
$expr: { $eq: ['$timestamp', '$$lastTimestamp'] }
} }
],
as: 'lastObjArr'
}
这里我有一个集合,比如说 test
,存储数据的字段名为 timestamp
(以毫秒为单位)。该集合中的文档以timestamp
间隔60000密集插入。也就是说,我总是可以找到一个并且只有一个文档其timestamp
比引用的文档早1分钟(除了第一个一,当然)。现在我想执行连接以将每个文档与 1 分钟前 timestamp
的文档相关联。我试过这种聚合:
...
$lookup : {
from: 'test',
let : { lastTimestamp: '$timestamp'-60000 },
pipeline : [
{$match : {timestamp:'$timestamp'}}
],
as: 'lastObjArr'
},
...
它打算找到文档的数组并将其设置为键lastObjArr
的值。但实际上 lastObjArr
始终是空的。发生什么事了?
您定义了一个名为“lastTimestamp”的变量并将其分配给
'$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'
},
您的 $lookup
管道不完整,因为它缺少必要的数学运算符。首先,由于多种因素,lastObjArr
为空,其中之一是表达式
let : { lastTimestamp: '$timestamp'-60000 },
计算不正确,需要使用$subtract
运算符
let : { lastTimestamp: { $subtract: ['$timestamp', 60000] } },
此外,$match
管道步骤需要使用 $expr
operator together with $eq
才能使查询正常工作,即
$lookup : {
from: 'test',
let : { lastTimestamp: { $subtract: ['$timestamp', 60000] } },
pipeline : [
{ $match : {
$expr: { $eq: ['$timestamp', '$$lastTimestamp'] }
} }
],
as: 'lastObjArr'
}