使用MongoDB聚合将两个列表合并到一个对象中

时间:2020-06-17 18:13:26

标签: mongodb aggregation-framework

我正在使用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,但没有成功。我可以使用什么运营商来从当前位置到达需要的位置?

1 个答案:

答案 0 :(得分:1)

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

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

Mongo Playground