使用 MongoDB 聚合时 - 如何过滤掉没有聚合 children 的结果?

When using MongoDB aggregation - How to filter out results with no aggregated children?

尝试着手研究聚合特性 无法弄清楚如何过滤结果 没有汇总 children?

假设我有 things:

{ _id: abc1, thingColor: "green" }
{ _id: abc2, thingColor: "red" }
{ _id: abc3, thingColor: "amazing" }

我有 birds:

{ _id: 1, thing_id: "abc1", type: "singing", isBiting: false }
{ _id: 2, thing_id: "abc1", type: "notFlying", isBiting: true }
{ _id: 3, thing_id: "abc3", type: "manEating", isBiting: false }

现在我想得到一个事物列表,但只有那些至少有一只鸟通过 id 与它们相关联并且只有会咬人的鸟。 所以基本上从这个例子我只想从 things 得到:

{ _id: abc1, birds_id: "abc1" }

我的查询是这样的-查询things:

  {
    $lookup:
      {
        from: 'birds',
        let: { thingIdVar: '$_id'},
        pipeline: [
          {$match:
              {$expr:
                  {$and: [
                      {$eq: ['$thing_id',  '$$thingIdVar']},
                      {$eq: ['$isBiting',  true]}
                    ]}
              }
          }
        ],
        as: 'birds'
      }
  },

这将 return thingsbirds 聚合,但它会返回所有内容,即使它们没有 birds 聚合。

如果我有 1 对 1 thingsbirds 我可以使用 {$unwind: '$birds'} 但是每个 thing 可以有很多 birds

此时,我正在以编程方式进行过滤,但这会弄乱其他一些东西(这个例子是一个简化版本)。

所以我更愿意从 mongo 得到已经过滤的结果..

有办法吗??

谢谢

$lookup

之后使用 $match 阶段
{ "$match": { "birds": { "$ne": [] }}}

由于父集合没有障碍,因此 returns 所有文档。因此,要过滤掉不包含至少一个 birds 的文档(事物),您必须在父集合

中使用 $match 阶段