是否有一种方法可以创建一个完全可选的聚合阶段,例如基于是否定义了变量?例如,如果存在字段,我可以让$ cond运算符继续进行管道聚合,否则返回根对象吗?
const thread = await BasePost.aggregate([
{
$match: { _id: ObjectId(_id) },
},
// if $parent exists, continue with pipeline
// else return $root object found
{
$graphLookup: {
from: 'baseposts',
startWith: '$parent',
connectFromField: 'parent',
connectToField: '_id',
as: 'anteriorThread',
},
},
{
$unwind: '$anteriorThread',
},
{
$sort: { 'anteriorThread.depth': 1 },
},
{
$group: {
_id: '$_id',
anteriorThread: { $push: '$anteriorThread' },
root: { $first: '$$ROOT' },
},
},
{
$project: {
finalAnterior: {
$concatArrays: ['$anteriorThread', ['$root']],
},
},
},
]);