$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.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $zip: { inputs: [ <array1>, <array2>, ... ], useLongestLength: <boolean>, defaults: [ <default>, ... ] } }

⚙️ Parameters

inputsThe list of arrays to merge.
useLongestLengthOptional boolean; true aligns to the longest array.
defaultsOptional 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏