我一直认为preserveNullAndEmptyArrays
会在不存在的记录上允许$lookup
并仍然返回主结果。
不幸的是在这种情况下我只从AAA获取数据 - 我想要来自AAA和BBB的数据。
属性表
{
_id: "AAA",
name: "Property AAA"
},
{
_id: "BBB",
name: "Property BBB"
}
hotdeal表
{
_id: "001",
property: "AAA",
active: true,
text: "very good deal"
}
汇总
db.property.aggregate([
{ $match: {} },
{
$lookup: {
from: "hotdeal",
localField: "_id",
foreignField: "property",
as: "hotdeals"
}
},
{
$unwind: {
path: "$hotdeals", preserveNullAndEmptyArrays: true
}
},
{
$match: {
"hotdeals.active": true
}
},
{
$project: {
_id : 0,
name : 1,
"text" : "$hotdeals.text"
}
}
])