liveBook · Manning

UNWIND

As explained in MongoDB 8.0 in Action, Third Edition

UNWIND is an SQL function that expands array-valued data into separate rows or records.

UNWIND expands an array-valued field into separate rows or documents, making nested array contents easier to analyze with SQL or aggregation pipelines. section 18.3.3 section 6.3

Use UNWIND when array elements need independent processing:

  • In Atlas SQL, place UNWIND in the FROM clause and specify the source, array path, optional index identifier, and OUTER option. section 18.3.3
  • In aggregation pipelines, $unwind converts one document containing an array into one document per array element. section 6.3
  • Filter arrays before $unwind when possible, reducing the number of generated documents and the workload of later stages. section 6.1.2
  • Remember that MongoDB $unwind omits null, missing, or empty array fields by default. section 6.3

Expand account products with Atlas SQL

For an account whose products are ["Derivatives", "CurrencyService", "InvestmentStock"], UNWIND produces three rows. Each row retains account_id and exposes one product value, allowing array data to resemble relational rows for filtering and analysis. section 18.3.3

Count array values with an aggregation pipeline

Use $unwind on accounts, group by the resulting account number, sum one for each occurrence, and sort counts descending. This turns arrays across many customer documents into frequency results. section 6.3

SELECT *
FROM UNWIND(<data source>
 WITH PATH => <array_path>,
 INDEX => <identifier>,
 OUTER => <bool>
)

Use the syntax reference to identify UNWIND's data-source, path, index, and outer-row controls. section 18.3.3

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains expansion behavior, syntax options, examples, counting, and filtering guidance, but does not detail execution internals.
Examples
Demonstrates customer account arrays, account-number frequency counts, and account product rows in Atlas SQL.
What it assumes
Assumes familiarity with documents, arrays, and basic SQL or aggregation syntax while demonstrating the expansion operation directly.
What you can do after
Apply it via Atlas SQL or MongoDB aggregation to expand arrays, then filter, group, count, sort, or analyze the resulting records.
How it connects
Connects UNWIND with arrays, aggregation pipelines, $group, $sum, sorting, SQL, and FLATTEN.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.