聚合管道中的可选中断

问题描述

我有以下管道:

  1. 匹配集合 collection1 中的单个文档。
  2. 获取密钥 k_id,即 ObjectId 并使用该 collection2_id 中查找另一个文档。
  3. $unwind 结果。

问题是,我不确定 k_id 是否存在,collection2 包含我查找的文档。在这种情况下,我想在第一步之后做一些检查并中断聚合管道。我没有找到任何具有类似功能的运算符。

现在我做了一些复杂的事情。

db['collection1'].aggregate([

  {$match: ...},// make field that always exist and put either $k_id or null there
  {$addFields: {
     k_id_ensured: {$ifNull: ['$k_id',null]}
  }},// $document_unensured may be empty array in case no documents found
  {$lookup: {
    from: 'collection2',...,as: 'document_unensured'
  }},// replace empty array with [null],...
  {$addFields: {
    document_ensured: {
       $cond: {
          // (if $document_unensured is empty array...)
          if: {$eq: [ {$size,'$document_unensured'},0 ]},// (...then make it contain at least `null`)
          then: [ null ],else: '$document_unensured'
       }
    }
  }},// ...because after unwinding empty array the whole
  // document will just dissappear
  {$unwind: {path: '$document_ensured'}},{$project: /*delete all non needed fields*/}

])

有没有更优雅的方法来做到这一点?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)