下面是一些中间管道的聚合
[
{
$unwind: "$destinations"
},
{
$lookup: {
from: "customers",
localField: "destinations.sold_to_id",
foreignField: "_id",
as: "sold_to_ref"
},
},
]
根据上面的查询,
destinations
是一个数组,就像
[{
type: 1,
sold_to_id: 'xxxxx'
},
{
type: 2,
sold_to_id: 'yyyy',
}
]
现在我想根据类型执行查找(即) 如果 type = 1,则从
customers
查找
否则从users
查找。
注:customers
和users
是两个不同的集合
请帮我解决这个问题。
提前致谢
编辑:
我试过的解决方案
[{
$unwind: "$destinations"
},
{
$lookup: {
from: "customers",
"let": {
type: "$destinations.type",
destination_id: "$destinations.sold_to_id"
},
pipeline: [
{
"$match": {
"$expr": { $and:
[
{ $eq: [ "$$type", 1 ] }, // Here I need to compare the type value with 1 which is not happening
{ $eq: [ "$_id", "$$destination_id" ] }
]
}
}
}
],
as: "sold_to_ref"
},
}]
解决方法: 你用
LEFT JOINS
运行 2 $facet
,合并它们并压平结果。
db.collection.aggregate([
{
$unwind: "$destinations"
},
{
$facet: {
users: [
{
$match: {
"destinations.type": 2
}
},
{
$lookup: {
from: "users",
localField: "destinations.sold_to_id",
foreignField: "_id",
as: "sold_to_ref"
}
}
],
customers: [
{
$match: {
"destinations.type": 1
}
},
{
$lookup: {
from: "customers",
localField: "destinations.sold_to_id",
foreignField: "_id",
as: "sold_to_ref"
}
}
]
}
},
{
$project: {
merge: {
$concatArrays: ["$users", "$customers"]
}
}
},
{
$unwind: "$merge"
},
{
$replaceWith: "$merge"
}
])