【发布时间】: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中执行此{ <pipeline stage 2> }两次。关于您的第二个选项,不确定它发生了什么/是否已优化 - 除非我们看到您的查询:-) 您可以使用我的答案,因为它就像基本的.find()一样,没有任何过滤器会返回所有通过的文档作为是.. -
是的,这就是我称之为“解决方法”的原因
标签: mongodb aggregation-framework facet