将mongodb聚合变量传递给NodeJ



我正在尝试基于Nodejs中聚合的属性在聚合中使用$gte。

const twelveHours = 12 * 60 * 60 * 1000;
const pipeline = [
{ $addFields: { 
twelveHoursBeforeStart: { $subtract: ['$startDate', twelveHours] } } // this works
},
{ match: { 
endDate: { $gte: new Date('$twelveHoursBeforeStart') }, // <- HERE pass a variable    
},
]

我尝试过不同的解决方案,比如:

{ match: { 
endDate: { $gte: '$twelveHoursBeforeStart' },
},

但它们中没有一个真正起的作用

您可以在$match阶段、中同时执行这两项操作

  • $expr表达式与聚合$gte运算符匹配,第一个参数为endDate,第二个条件为减法
const twelveHours = 12 * 60 * 60 * 1000;
const pipeline = [
{
$match: {
$expr: {
$gte: [
"$endDate",
{ $subtract: ["$startDate", twelveHours] }
]
}
}
}  
]

游乐场

最新更新