MongoDB collection data with multiple arrays:
{
"_id": ObjectId("61aa6bf1742b00f59b894eb7"),
"first": ["abc", "def", "ghi"],
"last": ["rst", "uvw", "xyz"],
"numb": ["12", "34", "56"]
}
Expected output where the data in the arrays should be in this format:
{
"first": "abc",
"last": "rst",
"numb": "12"
},
{
"first": "def",
"last": "uvw",
"numb": "34"
},
{
"first": "ghi",
"last": "xyz",
"numb": "56"
}
You can make use of
$zip
to "transpose" multiple arrays (as many as you'd like actually):This:
zip
s the 3 arrays such that elements at the same index will get grouped into the same sub-array.$unwind
s (explodes/flattens) those sub-arrays.transforms the resulting arrays into objects to fit your expected output format:
$zip
ping (again!) the keys we want to associate with the array's values (the keys:["first", "last", "numb"]
and the values:"$x"
)$replaceWith
the current document with the result of the$zip
.Note that prior to Mongo
4.2
, you can use$replaceRoot
instead of$replaceWith
.