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

时间:2018-10-15 11:28:54

标签: mongodb aggregation-framework

在我的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 }
},

2 个答案:

答案 0 :(得分:1)

您可以使用$unwind中的preserveNullAndEmptyArrays来实现:

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

答案 1 :(得分:0)

根据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
      }
    }])