Open In App

How to Use $unwind Operator in MongoDB?

MongoDB is a NoSQL database widely used for its powerful aggregation framework which allows for complex data manipulation and analysis. One of the key operators in MongoDB’s aggregation pipeline is $unwind, which is used to deconstruct arrays within documents.

In this article, we will learn about the $unwind operator by understanding their examples in different situations and so on.



What is $unwind Operator?

The syntax for the $unwind operator is as follows:

{ $unwind: "$arrayField" }

Explanation: Here the “arrayField” is the name of the array field to be deconstructed.



Examples of How to Use $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 students which contains various information.

Output:

[
{
"_id": 1,
"name": "Alice",
"subjects": ["Math", "Science"]
},
{
"_id": 2,
"name": "Bob",
"subjects": ["History", "Geography"]
},
{
"_id": 3,
"name": "Charlie",
"subjects": ["Math", "English", "Physics"]
},
{
"_id": 4,
"name": "David",
"subjects": ["Biology", "Chemistry"]
},
{
"_id": 5,
"name": "Eve",
"subjects": ["Math", "Chemistry", "Physics"]
}
]

Example 1: Counting the Number of Subjects for Each Student

db.students.aggregate([
{ $unwind: "$subjects" },
{ $group: { _id: "$name", totalSubjects: { $sum: 1 } } }
])

Output:

{ "_id": "Eve", "totalSubjects": 3 }
{ "_id": "Charlie", "totalSubjects": 3 }
{ "_id": "Bob", "totalSubjects": 2 }
{ "_id": "Alice", "totalSubjects": 2 }
{ "_id": "David", "totalSubjects": 2 }

Example 2: Finding the Most Common Subject Among Students

db.students.aggregate([
{ $unwind: "$subjects" },
{ $group: { _id: "$subjects", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 1 }
])

Output:

{ "_id": "Math", "count": 3 }

Example 3: Creating a List of Unique Subjects Across All Students

db.students.aggregate([
{ $unwind: "$subjects" },
{ $group: { _id: null, uniqueSubjects: { $addToSet: "$subjects" } } }
])

Output:

{ "_id": null, "uniqueSubjects": ["Math", "Science", "History", "Geography", "English", "Physics", "Biology", "Chemistry"] }

Conclusion

Overall, The $unwind operator is a powerful tool in MongoDB’s aggregation framework and it allowing for the efficient deconstruction of arrays within documents. Whether you’re working with single arrays, nested arrays, or performing advanced data analysis tasks, the $unwind operator provides a flexible solution. By mastering the usage of $unwind and combining it with other aggregation stages, you can perform complex data manipulation easily.

Article Tags :