Open In App

How to Use $unwind Operator in MongoDB?

Last Updated : 05 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB $unwind operator is an essential tool for handling arrays within documents. It helps deconstruct arrays, converting each array element into a separate document, which simplifies querying, filtering, and aggregation in MongoDB.

By understanding the MongoDB $unwind syntax users can utilize this operator to optimize their database queries. In this article, We will explore practical MongoDB $unwind examples, handling of empty arrays and missing fields and Working with embedded arrays

What is the MongoDB $unwind Operator?

The $unwind operator in MongoDB breaks down an array field into multiple documents, where each document contains one element from the original array. The array field is replaced with one element from the array for each new document. This transformation makes it easier to query, filter, and aggregate data allowing us to break down complex documents and perform operations on individual array elements.

Why Use $unwind?

  • Simplifies array handling – Convert nested data into a structured format.
  • Enhances query efficiency – Work with individual array elements instead of the whole array.
  • Enables better data analysis – Perform aggregation and transformations on array fields.
  • Supports advanced filtering – Easily apply conditions on array values.

Syntax:

{
$unwind: <field path>
}

Key Terms:

  • <field path> → Specifies the path to the array field to be unwound

Examples of Using $unwind Operator in MongoDB

To understand How to Use $unwind Operator in MongoDB collection we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called employee which contains various information.

Sample Collection: employees

[
{
"_id": ObjectId("..."),
"name": "Mikky",
"age": 31,
"phone_no": 8654793212,
"company": "javatpoint",
"skills": ["C", "C++", "PHP", "Java", ".Net"]
},
{
"_id": ObjectId("..."),
"name": "John",
"age": 28,
"phone_no": 1234567890,
"company": "techguy",
"skills": ["JavaScript", "Python", "Go"]
},
{
"_id": ObjectId("..."),
"name": "Alice",
"age": 26,
"phone_no": 9876543210,
"company": "webmasters",
"skills": []
},
{
"_id": ObjectId("..."),
"name": "David",
"age": 40,
"phone_no": 5647382910,
"company": "devteam",
"skills": ["Ruby", "PHP", "Node.js"]
}
]

Example 1: Using MongoDB $unwind on a Simple Array

When working with array fields, the $unwind operator helps convert each array element into a separate document. This makes it easier to query, filter, and analyze individual elements within the array. Let's use the $unwind operator to break down the skills array into individual documents.

Query:

db.employee.aggregate([
{
$unwind: "$skills"
}
]);

Output:

{
"_id": ObjectId("..."),
"name": "Mikky",
"age": 31,
"phone_no": 8654793212,
"company": "javatpoint",
"skills": "C"
}
{
"_id": ObjectId("..."),
"name": "Mikky",
"age": 31,
"phone_no": 8654793212,
"company": "javatpoint",
"skills": "C++"
}
{
"_id": ObjectId("..."),
"name": "Mikky",
"age": 31,
"phone_no": 8654793212,
"company": "javatpoint",
"skills": "PHP"
}
{
"_id": ObjectId("..."),
"name": "Mikky",
"age": 31,
"phone_no": 8654793212,
"company": "javatpoint",
"skills": "Java"
}
{
"_id": ObjectId("..."),
"name": "Mikky",
"age": 31,
"phone_no": 8654793212,
"company": "javatpoint",
"skills": ".Net"
}
{
"_id": ObjectId("..."),
"name": "John",
"age": 28,
"phone_no": 1234567890,
"company": "techguy",
"skills": "JavaScript"
}
{
"_id": ObjectId("..."),
"name": "John",
"age": 28,
"phone_no": 1234567890,
"company": "techguy",
"skills": "Python"
}
{
"_id": ObjectId("..."),
"name": "John",
"age": 28,
"phone_no": 1234567890,
"company": "techguy",
"skills": "Go"
}
{
"_id": ObjectId("..."),
"name": "David",
"age": 40,
"phone_no": 5647382910,
"company": "devteam",
"skills": "Ruby"
}
{
"_id": ObjectId("..."),
"name": "David",
"age": 40,
"phone_no": 5647382910,
"company": "devteam",
"skills": "PHP"
}
{
"_id": ObjectId("..."),
"name": "David",
"age": 40,
"phone_no": 5647382910,
"company": "devteam",
"skills": "Node.js"
}

Explanation:

  • The $unwind operator splits each array element into a separate document.
  • Each skills entry is now an individual document.
  • Documents with empty arrays (Alice) are omitted from the results

Example 2: Handling Empty Arrays

In MongoDB, when using $unwind on an empty array, the document is omitted from the output. This is an important consideration when designing queries, as it may lead to unintended data loss if not handled correctly. If we need to retain documents with empty arrays, we can use the preserveNullAndEmptyArrays option.

Query:

db.employee.aggregate([
{
$unwind: "$skills"
}
]);

Explanation:

If a document has an empty skills array, it will not appear in the output. To ensure such documents are retained, we need to modify the query accordingly. As seen previously, Alice’s document will not appear in the output because the skills array is empty.

Example 3: Using MongoDB $unwind on an Embedded Array

In many cases, documents contain nested arrays within objects, making it necessary to extract and analyze individual elements. The $unwind operator can be applied to embedded arrays, breaking them down into separate documents while preserving other fields.

Next, let’s create a new collection called products and populate it with some documents that include embedded arrays. We'll then apply $unwind to deconstruct these arrays for better queryability

Sample Collection: products

[
{
"_id": "1",
"items": [
{
"name": "copy",
"work": ["write", "office"],
"cost": 10,
"total_quantity": 5
},
{
"name": "pencil",
"work": ["write", "school"],
"cost": 2,
"total_quantity": 5
}
]
},
{
"_id": "2",
"items": [
{
"name": "monitor",
"work": ["college", "office"],
"cost": 5000,
"total_quantity": 1
},
{
"name": "mouse",
"work": ["laptop", "CPU"],
"cost": 300,
"total_quantity": 5
}
]
}
]

Query: Unwinding items array

db.products.aggregate([
{
$unwind: "$items"
}
]);

Output:

{
"_id": "1",
"items": {
"name": "copy",
"work": ["write", "office"],
"cost": 10,
"total_quantity": 5
}
}
{
"_id": "1",
"items": {
"name": "pencil",
"work": ["write", "school"],
"cost": 2,
"total_quantity": 5
}
}
{
"_id": "2",
"items": {
"name": "monitor",
"work": ["college", "office"],
"cost": 5000,
"total_quantity": 1
}
}
{
"_id": "2",
"items": {
"name": "mouse",
"work": ["laptop", "CPU"],
"cost": 300,
"total_quantity": 5
}
}

Explanation:

The $unwind operator splits the items array into separate documents. Each document now contains one item, making it easier to analyze and query each product individually.

Best Practices for Using $unwind Efficiently

  • Use $unwind only when necessary – It increases document count, which may impact performance.
  • Filter data first – Use $match before $unwind to reduce processing load.
  • Use indexing – Index frequently queried fields for better performance.
  • Leverage preserveNullAndEmptyArrays – To ensure no documents are lost when an array is empty.

Conclusion

Overall, MongoDB $unwind operator is crucial for improving data query efficiency and flexibility. By utilizing the MongoDB $unwind syntax and its applications in various scenarios, including embedded arrays, developers can enhance their data manipulation processes. By using $unwind, developers can efficiently break down complex documents, making data more accessible, easier to analyze, and more efficient to query. By integrating $unwind into your MongoDB workflow, we can enhance data processing, reporting, and analytics, making it an essential tool for every MongoDB developer.


Next Article
Article Tags :

Similar Reads