首页 > 解决方案 > MongoDB 聚合中 $lookup 集合的条件

问题描述

假设我有四个集合:一个Main集合和三个其他集合AB并且C

Main 集合有一个foreignKey字段指向或中的记录A,具体取决于字段:BCtype

Main
{_id: 1, foreignKey: 1, type: "TypeA"},
{_id: 2, foreignKey: 2, type: "TypeA"},
{_id: 3, foreignKey: 1, type: "TypeB"},
{_id: 4, foreignKey: 1, type: "TypeC"}


A
{_id: 1, otherData: "asdf"},
{_id: 2, otherData: "qwer"}

B
{_id: 1, otherData: "hello"},

C
{_id: 1, otherData: "world"}

我想$lookup在聚合内部执行连接。有没有办法让from字段依赖于字段的值type

此示例中的结果将是:

{_id: 1, foreignKey: 1, type: "TypeA", rest: {_id: 1, otherData: "asdf"}},
{_id: 2, foreignKey: 2, type: "TypeA", rest: {_id: 1, otherData: "qwer"}},
{_id: 3, foreignKey: 1, type: "TypeB", rest: {_id: 1, otherData: "hello"}},
{_id: 4, foreignKey: 1, type: "TypeC", rest: {_id: 1, otherData: "world"}}

标签: mongodbmongodb-queryaggregation-framework

解决方案


您不能从 $lookup 动态中获取。您可以在这里做的是对每个集合(A、B、C)进行 3 个查找阶段,然后在下一个投影阶段,您将知道根据您的“类型”属性从哪个字段获取值。为了确保良好的性能,您还可以做的是在这些外键的 A、B 和 C 集合中创建索引。


推荐阅读