猫鼬concat和数组中的单个元素

时间:2018-09-09 17:45:41

标签: mongodb mongoose aggregation-framework

这是一个分为两部分的mongoDB / mongoose问题

我想将名字/姓氏合并为“名称”,并且我只想显示数组中的单个“当前”项。

所以,如果我的数据看起来像这样

[{
    "fname":"bob",
    "lname":"jones",
    "role":"professional", 
    "active":true,
    "jobs":[{
        "job":"janitor",
        "current":true
    },{
        "job":"dog groomer"
        "current":false
    }]
},{
    "fname":"sally",
    "lname":"peterson",
    "role":"professional", 
    "active":true,
    "jobs":[{
        "job":"engineer",
        "current":false
    },{
        "job":"college admin"
        "current":true
    }]
},{
    "fname":"jackson",
    "lname":"smiley",
    "role":"professional", 
    "active":true,
    "jobs":[{
        "job":"car salesman",
        "current":false
    },{
        "job":"street sweeper"
        "current":false
    }{
        "job":"house painter"
        "current":true
    }]
},{
    "fname":"katie",
    "lname":"smiley",
    "role":"amature", 
    "active":true,
    "jobs":[{
        "job":"drone entheuast",
        "current":true
    }]
}]

我希望我的返回数据为

[{
    name:"bob jones", 
    job:"janitor"
},{
    name:"sally peterson", 
    job:"college admin"},
{
    name:"jackson smiley", 
    job:"house painter"
}]

当前-我正在使用这种猫鼬语法-但这还不够...

module.exports.getActiveList = function( callback ) {
        const query = { "role":"professional", "active":true }
        People.find( query, 'name job', callback );
    }

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

您可以使用$concatfnamelname组合为name$filter,以从jobs获取当前的活动作业数组

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

或者使用$let在一个阶段中完成

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