使用mongodb聚合将值与数组内的值映射

时间:2020-03-05 10:14:23

标签: mongodb mongodb-query aggregation-framework aggregate-functions

在记录中具有值。

_id:asdgrsdv
surname:cooper,
comapany:sabesto,
salary:15748
mapped:Array
0:Object
  name:'mark',
  age:'25',
  surname:'cooper'
1:Object
  name:'snow',
  age:'29',
  surname:'wyte'

如何在mongodb聚合中将surnamesurname中的mapped array映射到外部

必需的输出:

_id:asdgrsdv
  name:'mark',
  comapany:sabesto,
  salary:15748
  age:'25',
  surname:'cooper'

1 个答案:

答案 0 :(得分:0)

尝试这个:

db.collection.aggregate([
  {
    $addFields: {
      data: {
        $mergeObjects: [
          "$$ROOT",
          {
            $arrayElemAt: [
              {
                $filter: {
                  input: "$mapped",
                  cond: {
                    $eq: [
                      "$$this.surname",
                      "$surname"
                    ]
                  }
                }
              },
              0
            ]
          }
        ]
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  },
  {
    $project: {
      "mapped": 0
    }
  }
])

MongoPlayground