代码之家  ›  专栏  ›  技术社区  ›  Blue Bot

使用MongoDB聚合时-如何筛选没有聚合子级的结果?

  •  1
  • Blue Bot  · 技术社区  · 7 年前

    我正试图了解聚合特性 我很难弄清楚如何过滤结果 没有孩子?

    假设我有 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与它们关联,并且只有会咬人的鸟。 所以基本上从这个例子中,我想从 仅:

    { _id: abc1, birds_id: "abc1" }
    

    我的查询是这样的-查询

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

    这将返回 加上 但是它会把所有的东西都拿回来,即使他们没有 合计。

    如果我有1比1 {$unwind: '$birds'} 但每个 thing

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

    因此,我更希望从mongo获得已过滤的结果。。

    有没有办法做到这一点??

    谢谢

    1 回复  |  直到 7 年前
        1
  •  2
  •   Ashh    7 年前

    使用 $match 赛后舞台 $lookup

    { "$match": { "birds": { "$ne": [] }}}
    

    因为父集合没有障碍,所以它返回所有文档。因此,要过滤掉至少不包含一个的文档(内容) birds 你必须使用 父集合中的阶段