$zip
The $zip operator in Amazon DocumentDB allows you to combine multiple arrays into a single array of tuples (key-value pairs). This is useful when you need to create new documents or objects by combining data from different sources or arrays within a document.
Parameters
-
inputs: An array of expressions that resolve to arrays. These arrays will be combined into a single array of tuples. -
useLongestLength: (optional) Iftrue, the output array will have the length of the longest input array, padding shorter arrays withnullvalues. Iffalse, the output array will have the length of the shortest input array. -
defaults: (optional) An array of default values to use for the tuples if the corresponding input array is shorter than the longest input array anduseLongestLengthistrue.
Example (MongoDB Shell)
The following example demonstrates how to use the $zip operator to combine two arrays into a single array of tuples.
Create sample documents
db.grades.insert([ { "_id": 1, "name": "John", "scores": [90, 85, 92], "classes": ["Math", "English", "Science"] }, { "_id": 2, "name": "Jane", "scores": [88, 91, 90, 85], "classes": ["Math", "English", "Science", "History"] } ])
Query example
db.grades.aggregate([ { $project: { "name": 1, "scoredClasses": { $zip: { inputs: ["$scores", "$classes"], useLongestLength: true, defaults: [null, null] } } } } ])
Output
[
{
"_id": 1,
"name": "John",
"scoredClasses": [
[90, "Math"],
[85, "English"],
[92, "Science"],
[null, null]
]
},
{
"_id": 2,
"name": "Jane",
"scoredClasses": [
[88, "Math"],
[91, "English"],
[90, "Science"],
[85, "History"]
]
}
]
Code examples
To view a code example for using the $zip command, choose the tab for the language that you want to use: