尝试了解聚合功能 并无法弄清楚如何过滤结果 没有聚合的 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 things
到 birds
,我可以使用 {$unwind: '$birds'}
但每个事物
可以有很多鸟
此时,我以编程方式进行过滤,但这会弄乱其他一些东西(此示例是简化版本)。
所以我更愿意从已经过滤的 mongo 获得结果..
有办法吗?
谢谢
最佳答案
在$lookup
之后使用$match
阶段
{ "$match": { "birds": { "$ne": [] }}}
由于父集合没有障碍,因此它返回所有文档。因此,要过滤掉不包含至少一只 birds
的文档(事物),您必须在父集合中使用 $match
阶段
关于node.js - 使用 MongoDB 聚合时 - 如何过滤掉没有聚合子项的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53916452/