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.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read