首页 > 解决方案 > 使用 MongoDB Aggregation 将两个列表合并为一个对象

问题描述

我正在使用 mongoDB,并且我有类似于以下内容的文档

{
  "files": ["Customers", "Items", "Contacts"],
  "counts": [1354, 892, 1542],
  ...
}

并使用聚合管道阶段,我想将上述内容转换为更像..

{
  "file_info": [
    {"file_name": "Customers", "record_counts": 1354},
    {"file_name": "Items", "record_counts": 892},
    {"file_name": "Contacts", "record_counts": 1542}
  ]
}

我试过使用$map, $reduce, and $arrayToObject但没有任何成功。我可以使用哪些运算符从我当前所在的位置到达我需要的位置?

标签: mongodbaggregation-framework

解决方案


您可以使用$zip组合两个数组和$map以获得新结构:

{
    $project: {
        file_info: {
            $map: {
                input: { $zip: { inputs: [ "$files", "$counts" ] } },
                in: {
                    file_name: { $arrayElemAt: [ "$$this", 0 ] },
                    record_counts: { $arrayElemAt: [ "$$this", 1 ] },
                }
            }
        }
    }
}

蒙戈游乐场


推荐阅读