mongodb:如何提取字段而不是通过聚合+ $ lookup + $ project获得对象

时间:2018-09-21 06:03:15

标签: mongodb mongoose mongodb-query aggregation-framework

我有两个合同。

// UserInfo
{ _id: '1', name: 'Alice' }
{ _id: '2', name: 'Bob' }
{ _id: '3', name: 'Charlie' }

// Application
{ _id: '00', userId: '1', jobId: 'gg' }
{ _id: '01', userId: '1', jobId: 'fb' }
{ _id: '02', userId: '2', jobId: 'ms' }

我想得到:

{ name: 'Alice', jobIds: [ 'gg', 'fb' ] }
{ name: 'Bob', jobIds: [ 'ms' ] }
{ name: 'Charlie', jobIds: [] }

请注意,查理没有申请。

我当前的代码:

UserInfo.aggregate([
  {
    $lookup: {
      from: 'applications',
      let: { userId: '$_id' },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ['$userId', '$$userId'] }
          }
        },
        {
          $project: { jobId: 1, _id: 0 }
        }
      ],
      as: 'jobIds'
    }
  }
])

我知道了

{ _id: '1', name: 'Alice', jobIds: [ { jobId: 'gg' }, { jobId: 'fb' } ] }
{ _id: '2', name: 'Bob', jobIds: [ { jobId: 'ms' } ] }
{ _id: '3', name: 'Charlie', jobIds: [] }

如何获取jobIds: [ 'gg', 'fb' ]而不是jobIds: [ { jobId: 'gg' }, { jobId: 'fb' } ]

Aggregation Pipeline Stages中找不到正确的方法。

1 个答案:

答案 0 :(得分:2)

在管道的末尾使用$addFields阶段。

UserInfo.aggregate([
  { "$lookup": {
    "from": "applications",
    "let": { "userId": '$_id' },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$userId", "$$userId"] }}},
      { "$project": { "jobId": 1, "_id": 0 }}
    ],
    "as": "jobIds"
  }},
  { "$addFields": { "jobIds": "$jobIds.jobId" }}
])