繁体   English   中英

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

[英]How to merge two arrays of objects by the same field using MongoDB aggregation?

我有两个 arrays:

[
  {
    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。

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

要按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
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Mongo游乐场| Arrays 同 position + name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM