繁体   English   中英

使用 MongoDB 聚合将两个列表合并为一个 object

[英]Using MongoDB Aggregation to merge two lists into an object

我正在使用 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但没有任何成功。 我可以使用哪些运算符从我当前所在的位置到达我需要的位置?

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

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

蒙戈游乐场

暂无
暂无

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

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