【问题标题】:How to return the input document in $facet如何在 $facet 中返回输入文档
【发布时间】:2020-05-20 12:04:48
【问题描述】:

我正在寻找一种以$facet 聚合返回输入文档的智能方法。像这样的:

db.collection.aggregate([
   { <pipeline stage 1> },
   { <pipeline stage 2> },
   {
      $facet:
         {
            outputField1: [ output of <pipeline stage 2> ],
            outputField2: [ { <pipeline stage 3> } ]
         }
   }
])

我尝试了outputField1: [ $$CURRENT ] 之类的方法,但没有成功。

实际上我找到了两种解决方法,但我想知道是否有更聪明的方法。

db.collection.aggregate([
   { <pipeline stage 1> },
   {
      $facet:
         {
            outputField1: [ { <pipeline stage 2> } ],
            outputField2: [ { <pipeline stage 2> }, { <pipeline stage 3> } ]
         }
   }
])


db.collection.aggregate([
   { <pipeline stage 1> },
   { <pipeline stage 2> },
   {
      $facet:
         {
            outputField1: [ { $unset: "a_dummy_field_which_does_not_exist" } ],
            outputField2: [ { <pipeline stage 3> } ]
         }
   }
])

【问题讨论】:

  • 不需要在outputField1 和outputField2 中执行此{ &lt;pipeline stage 2&gt; } 两次。关于您的第二个选项,不确定它发生了什么/是否已优化 - 除非我们看到您的查询:-) 您可以使用我的答案,因为它就像基本的 .find() 一样,没有任何过滤器会返回所有通过的文档作为是..
  • 是的,这就是我称之为“解决方法”的原因

标签: mongodb aggregation-framework facet


【解决方案1】:

您也可以这样做{ $match: {} } 以按原样返回当前文档:

{
    $facet:
    {
        outputField1: [{ $match: {} }],
        outputField2: [ { <pipeline stage 3> } ] } } }]
    }
}

【讨论】:

  • 是的,{ $match: {} } 也类似于null 操作。实际上我希望使用一个全局常量——也许它不存在。
  • @WernfriedDomscheit :这是我唯一能想到的,因为如果你想使用任何运算符,那么它必须在像 '$project' 这样的阶段使用,它会创建一个数组 outputField1的对象。或者您可以使用 group + push & root 投影一个字段,但这也会在 outputField1 数组中创建一个对象!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
相关资源
最近更新 更多