【问题标题】:Using MongoDB Aggregation to merge two lists into an object使用 MongoDB Aggregation 将两个列表合并为一个对象
【发布时间】:2020-06-18 02:19:21
【问题描述】:

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

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案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

    【讨论】:

    • 刚刚测试过,效果很好,谢谢!也感谢您向我介绍 mongoplayground,非常有用的工具!
    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2021-12-18
    相关资源
    最近更新 更多