【问题标题】:How to merge two arrays of objects by the same field using MongoDB aggregation?如何使用 MongoDB 聚合通过同一字段合并两个对象数组?
【发布时间】:2020-09-03 02:00:15
【问题描述】:

我有两个数组:

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

聚合框架有没有一种巧妙的方法来实现这一点?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    要通过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

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 1970-01-01
      • 2021-12-12
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 2021-06-26
      相关资源
      最近更新 更多