如何使用MongoDB聚合通过同一字段合并两个对象数组?

时间:2020-04-18 15:43:59

标签: mongodb aggregation-framework

我有两个数组:

[
  {
    name: 'First object',
    value: 1
  },
  {
    name: 'Second object',
    value: 2
  },
  {
    name: 'Third object',
    value: 3
  },
];

[
  {
    name: 'First object',
    anotherValue: 1,
  },
  {
    name: 'Second object',
    anotherValue: 2,
  },
  {
    name: 'Third object',
    anotherValue: 3,
  },
];

我可以使用MongoDB聚合使用这两个来获取新数组吗?我的意思是:

[
  {
    name: 'First object',
    value: 1,
    anotherValue: 1,
  },
  {
    name: 'Second object',
    value: 2,
    anotherValue: 2,
  },
  {
    name: 'Third object',
    value: 3,
    anotherValue: 3,
  },
];

我尝试使用facetconcatArraysgroup来获取该数组,但是它不起作用:

{
  $facet: {
    $firstArray: [...],
    $secondArray: [...],
  }
  $project: {
    mergedArray: {
      $concatArrays: [firstArray, secondArray],
    }
  },
  $group: {
    _id: {
      name: '$mergedArray.name'
    },
    value: {
      $first: '$mergedArray.value'
    },
    anotherValue: {
      $first: '$mergedArray.anotherValue'
    }
  },
}

但是$anotherValue始终为空。

是否有通过聚合框架实现此目标的简便方法?

1 个答案:

答案 0 :(得分:0)

要通过name进行匹配,请运行以下查询:

db.collection.aggregate([
  {
    $project: {
      anotherValue: {
        $map: {
          input: "$firstArray",
          as: "one",
          in: {
            $mergeObjects: [
              "$$one",
              {
                $arrayElemAt: [
                  {
                    $filter: {
                      input: "$secondArray",
                      as: "two",
                      cond: { $eq: ["$$two.name", "$$one.name"]}
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  }
])

MongoPlayground | Arrays with the same position + name value