1

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"
        }
    }
];
4
  • Can there be more values in name and values array? Can they mismatch in size? Commented Mar 1, 2021 at 14:23
  • No, they cannot mismatch the size, the Array length of the values and name should be the same. Commented Mar 1, 2021 at 14:25
  • And what about the count always two? Commented Mar 1, 2021 at 14:25
  • the array count can be more, but the count should be the match of both arrays Commented Mar 1, 2021 at 14:26

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.