简体   繁体   English

将Array结构归一化为mongoDB中的多个文档

[英]Normalized the Array structure into Multiple documents in mongoDB

Input is Once Document输入是一次文档

{
  "name": [
    "abc",
    "xyz"
  ],
  "values": [
    "123",
    "100"
  ]
}

The explanation I want to Normalize the Array into multiple documents, abc , and xyz are dynamically coming, these are user define parameters解释我想将数组规范化为多个文档, abcxyz是动态来的,这些是用户定义的参数

Expected Output预计 Output

[
    {
        "data": {
            "name": "abc",
            "values": "123"
        }
    },
    {
        "data": {
            "name": "xyz",
            "values": "100"
        }
    }
];

What you want to do is use $zip , like so:您要做的是使用$zip ,如下所示:

db.collection.aggregate([
  {
    $project: {
      data: {
        $map: {
          input: {
            $zip: {
              inputs: [
                "$name",
                "$values"
              ]
            }
          },
          as: "zipped",
          in: {
            name: {
              "$arrayElemAt": [
                "$$zipped",
                0
              ]
            },
            values: {
              "$arrayElemAt": [
                "$$zipped",
                1
              ]
            }
          }
        }
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceRoot: {
      newRoot: {
        data: "$data"
      }
    }
  }
])

Mongo Playground蒙戈游乐场

Try this:尝试这个:

db.testCollection.aggregate([
    {
        $project: {
            "data": {
                $map: {
                    input: { $zip: { inputs: ["$name", "$values"] } },
                    as: "item",
                    in: {
                        name: { $arrayElemAt: ["$$item", 0] },
                        values: { $arrayElemAt: ["$$item", 1] }
                    }
                }
            }
        }
    },
    { $unwind: "$data" }
]);

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

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