$zip (Merge Multiple Arrays by Position)
Last updated: 2026-10-09
$zip (Merge Multiple Arrays by Position)
$zip merges several arrays by position into groups, each holding the element at the same index from every input — a vertical alignment of arrays. It truncates at the shortest array by default; setting useLongestLength to true aligns to the longest and fills missing slots from defaults. Typical uses: pairing name arrays with score arrays or joining two time series. defaults must have the same number of elements as inputs.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $zip: { inputs: [ <array1>, <array2>, ... ], useLongestLength: <boolean>, defaults: [ <default>, ... ] } }
⚙️ Parameters
| inputs | The list of arrays to merge. |
|---|---|
| useLongestLength | Optional boolean; true aligns to the longest array. |
| defaults | Optional default values filling shorter arrays; must match the count of inputs. |
Returns:An array grouped by position; null when any input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $zip: pair names with scores
db.students.aggregate([
{ $project: {
pairs: { $zip: { inputs: ['$names', '$scores'] } }
} }
])
Output:
{ '_id': 1, 'pairs': [ [ 'alice', 90 ], [ 'bob', 85 ] ] }
📌 Notes
- Truncates at the shortest array by default, dropping excess elements
- With useLongestLength true, provide defaults or missing slots become null
- defaults must have exactly as many elements as inputs
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat happens when arrays differ in length?
ATruncates at the shortest by default; set useLongestLength true and supply defaults.
QWhat do defaults do?
AThey fill missing slots in shorter arrays and must match the input count.
QHow does $zip differ from $concatArrays?
A$zip aligns arrays vertically into tuples; $concatArrays chains them horizontally into one long array.