如何使用MongoDB聚合将两个对象数组按相同字段合并?

4

我有两个数组:

[
  {
    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始终为null。

在聚合框架中有没有一种简洁的方法可以实现这个功能?

1个回答

10

要按 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 | 具有相同位置和名称值的数组


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接