Zip two arrays and create new array of object in a reshaped form with MongoDB

To zip two arrays and create a new array of objects in MongoDB, use the $zip operator within an aggregation pipeline. This combines elements from multiple arrays at corresponding positions into a single reshaped structure.

Syntax

db.collection.aggregate([
    {
        $project: {
            "newFieldName": {
                $map: {
                    input: { $zip: { inputs: ["$array1", "$array2"] } },
                    as: "pair",
                    in: { field1: { $arrayElemAt: ["$$pair", 0] }, field2: { $arrayElemAt: ["$$pair", 1] } }
                }
            }
        }
    }
]);

Sample Data

db.demo339.insertOne({
    Id: 101,
    Score1: ["98", "56"],
    Score2: [67, 89]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e529ee5f8647eb59e5620a2")
}

Display Current Document

db.demo339.find();
{
    "_id": ObjectId("5e529ee5f8647eb59e5620a2"),
    "Id": 101,
    "Score1": ["98", "56"],
    "Score2": [67, 89]
}

Example: Zip Arrays with $map and $arrayElemAt

db.demo339.aggregate([
    {
        $project: {
            "AllArrayObject": {
                $map: {
                    input: { $zip: { inputs: ["$Score1", "$Score2"] } },
                    as: "pair",
                    in: {
                        Score1: { $arrayElemAt: ["$$pair", 0] },
                        Score2: { $arrayElemAt: ["$$pair", 1] }
                    }
                }
            }
        }
    }
]);
{
    "_id": ObjectId("5e529ee5f8647eb59e5620a2"),
    "AllArrayObject": [
        { "Score1": "98", "Score2": 67 },
        { "Score1": "56", "Score2": 89 }
    ]
}

How It Works

  • $zip combines arrays element by element: [["98", 67], ["56", 89]]
  • $map iterates through each paired array
  • $arrayElemAt extracts elements at index 0 and 1 from each pair

Conclusion

Use $zip with $map to combine corresponding elements from multiple arrays into structured objects. This technique is useful for reshaping data where related values exist in separate arrays.

Updated on: 2026-03-15T02:32:55+05:30

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements