bc110402922
bc110402922

Reputation: 457

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

Expected Output

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

Upvotes: 1

Views: 133

Answers (2)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

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" }
]);

Upvotes: 1

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

What you want to do is use $zip, like so:

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

Upvotes: 1

Related Questions