Mongodb聚合管道条件阶段

时间:2020-08-03 22:28:51

标签: javascript node.js mongodb mongoose

是否有一种方法可以创建一个完全可选的聚合阶段,例如基于是否定义了变量?例如,如果存在字段,我可以让$ 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']],
          },
        },
      },
    ]);

0 个答案:

没有答案