我希望能够在Mongoose聚合查询中使用先前计算的值,例如:
const aggregate = await Model.aggregate([
{
$group: {
_id: { id: `$id` },
timeStart: {
$min: `$aTime`,
},
timeLatest: {
$max: `$aTime`,
},
timeLength: {
$subtract: [`$timeStart, $timeLatest`,],
},
},
},
]);
这显然不起作用-正确的语法是什么?
在这种情况下有一个单独的操作符:$addFields
const aggregate = await Model.aggregate([
{
$group: {
_id: { id: `$id` },
timeStart: {
$min: `$aTime`,
},
timeLatest: {
$max: `$aTime`,
},
},
{
$addFields: {
difference: { $subtract: [`$timeLatest`, `$timeStart`] },
},
},
},
]);