在MongoDB视图中使用$unwind时被排除的数据



在我的MongoDB后端中,我定义了一个返回员工列表的Mongo视图。我遇到的一个问题是,如果我在某个聚合阶段使用后跟$lookup$unwind,并且该特定人员还没有该属性的任何数据,那么他们将被排除在返回的数据之外。我说的是这样的聚合:

{
$lookup: { "from" : "departments", "localField" : "department", "foreignField" : "_id", "as" : "department" }
},
{
$unwind: { "path" : "$department" }
}, 

有没有办法解决这个问题:我可以在这里使用$lookup$unwind,同时如果他们碰巧没有该字段的任何数据,也不会排除该人?这会在这里完成,还是在我稍后调用的$project阶段(见下面的代码(?

{
$project: { "name" : 1.0, "department" : { "name" : "$department.name" }, "branch" : { "name" : "$branch.name" }, "addresses" : 1.0, "notes" : 1.0, "phones" : 1.0, "emails" : 1.0, "updatedAt" : 1.0 }
},

您可以使用$unwindpreserveNullAndEmptyArrays来实现此目的:

{
$lookup: { 
"from" : "departments", 
"localField" : "department", 
"foreignField" : "_id", 
"as" : "department" }
},
{
$unwind: { 
"path" : "$department",
"preserveNullAndEmptyArrays": true
}
}, 

根据 MongoDB 的文档

If you specify a path for a field that does not exist in an input document or the field 
is an empty array, $unwind, by default, ignores the input document
and will not output documents for that input document.
New in version 3.2: To output documents where the array field is missing, 
null or an empty array, use the option preserveNullAndEmptyArrays.

您可以尝试执行以下聚合查询

db.collection.aggregate([
{
$lookup: { 
"from" : "departments", 
"localField" : "department", 
"foreignField" : "_id", 
"as" : "department" }
},
{
$unwind: { 
"path" : "$department",
"preserveNullAndEmptyArrays": true
}
}])

最新更新