我有MongoDB的查询
Job.aggregate([
{$match: {created_by: req.params.userId }},
{$lookup: {
from: "users",
localField: "applicant._id",
foreignField: "_id",
as: "applicant" }},
{$unwind: '$applicant'}
])
如果申请者的ID为空,它将不起作用。这不是我想要的,如何使$lookup成为可选的?
最佳答案
$lookup
执行外部联接,如果没有匹配,则不会进行筛选。
问题在于$unwind
,它将在数组为空或为空时进行筛选,为了不筛选需要在preserveNullAndEmptyArrays : true
管道中指定$unwind
的空数组
Job.aggregate([
{$match: {created_by: req.params.userId }},
{$lookup: {
from: "users",
localField: "applicant._id",
foreignField: "_id",
as: "applicant" }
},
{$unwind: {
path :'$applicant',
preserveNullAndEmptyArrays: true}
}
])