MongoDB 聚合,如何return 不受影响的项目

MongoDB Aggregation, how to return unaffected items

我有一个集合,其中的数据如下所示

{
    "fname":"bob",
    "lname":"jones",
    "role":"professional", 
    "active":true,
    "jobs":[{
        "job":"janitor",
        "current":true
    },{
        "job":"dog groomer"
        "current":false
    }]
}

我正在使用 "aggregate" 连接和剔除一些显示端不需要的数据 - 并返回一个简化的对象数组。

People.aggregate([
  { "$match": { "role": "professional", "active": true }},
  { "$project": {
    "name": { "$concat": ["$fname", " ", "$lname"] },
    "jobs": {
      "$filter": {
        "input": "$jobs",
        "as": "job",
        "cond": { "$eq": ["$$job.current", true] }
      }
    }
  }},
  { "$project": { 
    "name": 1, 
    "job": { "$arrayElemAt": ["$jobs.job", 0] }
  }}
])

但是,我也想传回 People 对象中的其他项目。 它们是否需要通过整个管道? 如果我也将这些字段添加到第一个 $project - 那么只有其中一个返回...

所以现在这个

People.aggregate([
  { "$match": { "role": "professional", "active": true }},
  { "$project": {
    "name": { "$concat": ["$fname", " ", "$lname"] },
    "jobs": {
      "$filter": {
        "input": "$jobs",
        "as": "job",
        "cond": { "$eq": ["$$job.current", true] }
      }
    },
    "role":"$role",
    "active":"$active"
  }},
  { "$project": { 
    "name": 1, 
    "job": { "$arrayElemAt": ["$jobs.job", 0] },
    "role":"$role",
    "active":"$active"
  }}
])

给我:

name 
job 
role

我错过了什么?

使用 $addFields instead of $project and use $project 排除 lname 和 fname 字段。

所以像

People.aggregate([
  {"$match":{"role":"professional","active":true}},
  {"$addFields":{
    "name":{"$concat":["$fname"," ","$lname"]},
    "job":{
      "$let":{
        "vars":{
          "jobs":{
            "$arrayElemAt":[
              {"$filter":{
                "input":"$jobs",
                "cond":{"$eq":["$$this.current",true]}
              }},
              0
            ]
          }
        },
        "in":"$$jobs.job"
      }
    }
  }},
  {"$project":{"fname":0,"lname":0}}
])