$unwind

The $unwind operator is a powerful aggregation pipeline stage in MongoDB that allows you to deconstruct an array field from input documents and generate a new document for each element in the array, essentially “unwinding” the array.

This operator is particularly useful when you have documents containing array fields, and you need to perform operations on the individual elements within those arrays. $unwind enables you to flatten the array structure and easily manipulate or analyze data within arrays as separate documents.

Syntax

The general syntax for the $unwind operator is:

{
  $unwind: {
    path: <field path>,
    includeArrayIndex: <string>, // Optional
    preserveNullAndEmptyArrays: <boolean> // Optional
  }
}

Parameters

Example

Consider a sales collection with the following sample document:

{
  _id: 1,
  item: "itemA",
  orders: [
    { quantity: 2, unitPrice: 10 },
    { quantity: 3, unitPrice: 20 },
    { quantity: 1, unitPrice: 15 }
  ]
}

If you want to calculate the total revenue for each individual order, you can use the $unwind operator to deconstruct the orders array:

db.sales.aggregate([{ $unwind: { path: '$orders' } }]);

The output will be:

[
  { _id: 1, item: 'itemA', orders: { quantity: 2, unitPrice: 10 } },
  { _id: 1, item: 'itemA', orders: { quantity: 3, unitPrice: 20 } },
  { _id: 1, item: 'itemA', orders: { quantity: 1, unitPrice: 15 } },
];

Now each document represents a single order, and you can easily perform further operations like calculating the revenue for each document.

Remember, the $unwind operator is a crucial tool for handling and analyzing array data in MongoDB, enabling you to efficiently work with complex data structures.