MongoDB聚合中$lookup上的条件从集合
假设我有四个集合:aMongoDB聚合中$lookup上的条件从集合,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,假设我有四个集合:aMain集合和另外三个a,B和C 主集合有一个foreignKey字段,该字段指向a、B或C中的记录,具体取决于字段类型: Main {_id: 1, foreignKey: 1, type: "TypeA"}, {_id: 2, foreignKey: 2, type: "TypeA"}, {_id: 3, foreignKey: 1, type: "TypeB"}, {_id: 4, foreignKey: 1,
Main
集合和另外三个a
,B
和C
主集合有一个foreignKey
字段,该字段指向a
、B
或C
中的记录,具体取决于字段类型
:
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"}}
我不知道我是否理解,但是。。。你是说这个吗
db.Main.aggregate([
{
“$match”:{
“类型”:“类型C”
}
},
{
“$lookup”:{
“from”:“C”,
“localField”:“foreignKey”,
“外域”:“\u id”,
“作为”:“输出”
}
}
])
仅使用所需类型而不是所有类型执行$lookup
例如
如果没有
$match
阶段,输出将包含所有类型()您无法在$lookup dynamic中使用。在这里,您可以对每个集合(A、B、C)执行3个查找阶段,然后在下一个投影阶段,您将知道根据“类型”属性从哪个字段获取值。为了确保良好的性能,您还可以在这些外键的A、B和C集合中创建索引。谢谢。差不多了。我想要,但每种类型都要。比如说,我想做三个匹配并连接结果