我创建了以下 View 。如果不是我仍然想要 orderheader 文档,我想让所有客户都使用 addresstype billing。我认为匹配阶段正在消除少数文件,因为少数文件没有地址类型计费。
我的意思是它的行为类似于 INNER JOIN,而不是我想要 LEFT JOIN。努力尝试,但我得到的只是 INNER JOIN。
db.createView(
"VWOrderHeader",
"OrderHeader",
[
{
$lookup:{
from:"AddressDoc",
as: "Address",
localField: "CustomerNo",
foreignField: "CustomerNo"
}
},
{
$match:{ "Address.AddressType":/Billing/i }
},
{
$project:{
_id:0,
CustomerNo :"$CustomerNo",
ContactName:{ $ifNull:[{$arrayElemAt: [ "$Address.ContactName",0 ]},""]}
}
}
]
)}
最佳答案
重新编写查询为
db.createView(
"VWOrderHeader",
"OrderHeader",
[
{
$lookup:{
from:"AddressDoc",
as: "Address",
localField: "CustomerNo",
foreignField: "CustomerNo"
}
},
{ $unwind: { path: "$Address", preserveNullAndEmptyArrays: true } },
{
$match:{ $or:[ {"Address.AddressType":/billing/i},{"Address.AddressType":""},{"Address.AddressType":null}] }
},
{
$project:{
_id:0,
CustomerNo :"$CustomerNo",
ContactName:{ $ifNull:[ "$Address.ContactName",""]}
}
}
]
)}
关于sql - 如何使用 $lookup MongoDB 进行 LEFT JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48453331/