Definition
Returns an array of the concatenated array values from documents in a window.
Note
Disambiguation
This page describes $concatArrays when used as a window
function.
You can also use $concatArrays in these other contexts:
$concatArrays (accumulator), which concatenates the array values from a field across a group of documents.$concatArrays (expression), which concatenates two or more arrays into a single array within a single document.
Syntax
{ $setWindowFields: { ... output: { <field>: { $concatArrays: "<array field>" } } } }
Behavior
Arguments that are null or resolve to null are included in the results. Arguments that refer to a field that is missing are not included in the results.
Example
The following example uses the movies collection from the sample_mflix
sample dataset. For details on how to load this dataset into your deployment, see Load the sample dataset.
The example uses $setWindowFields to partition movies by release year and concatenate the genres arrays within each partition, sorted by title. Each document receives the concatenation of the genres arrays from the first movie in its partition through the current document:
db.movies.aggregate( [ { $match: { year: { $in: [1914, 1915] } } }, { $setWindowFields: { partitionBy: { year: "$year" }, sortBy: { title: 1 }, output: { combinedGenres: { $concatArrays: "$genres", window: { documents: ["unbounded", "current"] } } } } }, { $project: { _id: 0, year: 1, title: 1, combinedGenres: 1 } } ] )
The preceding pipeline:
Uses
$setWindowFieldsto partition movies byyearwithpartitionByand sort each partition bytitle. The stage applies$concatArraysto thegenresfield over a documents window of[ "unbounded", "current" ]. ThecombinedGenresfield holds the concatenated genres from the first movie in the partition through the current document.Uses
$projectto includeyear,title, andcombinedGenresin the output.
The combinedGenres array grows within each partition as each document contributes its genres array.