简体   繁体   English

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

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

I'm using mongoDB and I have documents similar to the following我正在使用 mongoDB 并且我有类似于以下的文档

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

And using an aggregation pipeline stage, I want to convert the above into something more like..并使用聚合管道阶段,我想将上述内容转换为更像..

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

I've tried using $map, $reduce, and $arrayToObject but without any success.我尝试过使用$map, $reduce, and $arrayToObject但没有任何成功。 What operators can I use to get from where I currently am to where I need to be?我可以使用哪些运算符从我当前所在的位置到达我需要的位置?

You can use $zip to combine two arrays and $map to get the new structure:您可以使用$zip组合两个 arrays 和$map以获得新结构:

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

Mongo Playground蒙戈游乐场

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

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