可能为空的属性上的聚合

时间:2019-02-28 16:32:09

标签: mongodb aggregate

我正在尝试从两个集合中聚合属性,其中一个包含一个文档中可能存在或可能不存在的字段。当文档中没有该属性时,它根本不会返回任何文档。因此,我需要创建一种null检查,如果该属性不存在,请不要考虑该属性,否则请考虑一下,这是我的查询-

db.collection(collectionName).aggregate(
      [{
        $match: selector
      }, {
        $lookup: {
          from: 'status',
          localField: 'candidateId',
          foreignField: 'candidateId',
          as: 'profile'
        }
      }, {
        $project: {
          '_id': 0,

          'currentStatus': '$profile.currentStatus',
          'lastContacted': '$profile.lastContacted',
          'lastWorkingDay': '$profile.lastWorkingDay',
          'remarks': '$profile.remarks'
        }
      },{
         $unwind: '$lastWorkingDay'
      } 

在这种情况下,lastWorkingDay(如果不存在)会使整个查询不返回任何内容。任何指针都会有所帮助。

1 个答案:

答案 0 :(得分:1)

我认为您的查询有其他问题。 没有任何数据输入,这很难分析,所以我自己做了:

我刚刚在我的本地机器上尝试了此操作,并且它执行您期望的方式。

投影不应删除任何结果。这是我的示例:

集合c1:

/* 1 */
{
    "_id" : ObjectId("5c780eea79e5bed2bd00f85e"),
    "candidateId" : "id1",
    "currentStatus" : "a",
    "lastContacted" : "b"
}

/* 2 */
{
    "_id" : ObjectId("5c780efb79e5bed2bd00f863"),
    "candidateId" : "id2",
    "currentStatus" : "a",
    "lastContacted" : "b",
    "lastWorkingDay" : "yesterday"
}

集合C2:

/* 1 */
{
    "_id" : ObjectId("5c780f0a79e5bed2bd00f874"),
    "candidateId" : "id1"
}

/* 2 */
{
    "_id" : ObjectId("5c780f2879e5bed2bd00f87b"),
    "candidateId" : "id2"
}

汇总:

db.getCollection('c2').aggregate( [
    {$match: {}},
    { $lookup: {
            from: "c1",
            localField: "candidateId",
            foreignField: "candidateId",
            as : "profile"

        } },
    {$project: {
            _id: 0,
        "currentStatus" : "$profile.currentStatus",
        "lastWorkingDay" : "$profile.lastWorkingDay"

        } }

] )

结果:

/* 1 */
{
    "currentStatus" : [ 
        "a"
    ],
    "lastWorkingDay" : []
}

/* 2 */
{
    "currentStatus" : [ 
        "a"
    ],
    "lastWorkingDay" : [ 
        "yesterday"
    ]
}

如您所见,对于聚合中的两个值,lastWorkingDay均正确执行。

请注意,由于查询可能有多个结果,因此查询正在为profiles创建一个数组。如果需要更详细的信息,则可能需要unwind

我希望这会有所帮助。