node.js - 使用 MongoDB 聚合时 - 如何过滤掉没有聚合子项的结果?

标签 node.js mongodb mongoose lookup

尝试了解聚合功能 并无法弄清楚如何过滤结果 没有聚合的 child ?

假设我有东西:

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

我有:

{ _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'
      }
  },

这将返回与birds聚合的things,但它会返回所有的东西,即使它们没有聚合birds .

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

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

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

有办法吗?

谢谢

最佳答案

$lookup之后使用$match阶段

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

由于父集合没有障碍,因此它返回所有文档。因此,要过滤掉不包含至少一只 birds 的文档(事物),您必须在父集合中使用 $match 阶段

关于node.js - 使用 MongoDB 聚合时 - 如何过滤掉没有聚合子项的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53916452/

相关文章:

javascript - 将对象插入对象数组

node.js - Mongoose 错误: Property 'Buffer' does not exist on type 'typeof globalThis'

javascript - IBM Watson Visual Recognition - 由于凭证无效,访问被拒绝

node.js - 不使用模板引擎的 Koa 渲染

mongodb - 排除 MongoDB 中嵌入文档的单个字段以外的所有字段

mysql - SailsJS 1.0 : Error in . create() Mongo 中的模型与存储在 MySQL 中的模型的单向关联

node.js - NodeJS 中未确认电子邮件时自动删除 Mongo 文档

javascript - 从 MongoDB 查询数据到 Javascript

string - 将 UUID 转换为 String 以插入 mongodb

node.js - 错误 : Can't set headers after they are sent , 仅在刷新页面后发生