【发布时间】:2021-02-22 22:52:55
【问题描述】:
假设我有四个集合:一个Main 集合和另外三个A、B 和C
主集合有一个foreignKey 字段,它指向A、B 或C 中的记录,具体取决于字段type:
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"}}
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework