In this tutorial, we will learn about an aggregation stage MongoDB $unwind operator. To understand this topic we assume that you have a basic understanding of how to fetch or read documents from a collection.
Before going further, please make sure to install MongoDB on your computer.
What is MongoDB $unwind Operator
Definition
MongoDB $unwind operator is used to deconstructing an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.
Simply you can say the MongoDB $unwind duplicates each document in the pipeline, once per array element.
To understand the concept of $unwind operator, let’s take an example and understand it step by step.
Let’s create a users collection with the document. To create a collection with a document the query is like:
db.users.insertOne( { "name": "Avinash", "age": 27, "company": "Techy Hunger", "skills": ["Java", "MongoDB", "Node", "Angular"] } );
Now display documents from users collection using find() method.
db.users.find({}).pretty()
{ "_id" : ObjectId("5d958cdc446a46c989b98887"), "name" : "Avinash", "age" : 27.0, "company" : "Techy Hunger", "skills" : [ "Java", "MongoDB", "Node", "Angular" ] }
db.users.aggregate({ $project: { name: 1, age: 1, skills: 1 }}, { $unwind: "$skills" } )
/* 1 */ { "_id" : ObjectId("5d958cdc446a46c989b98887"), "name" : "Avinash", "age" : 27.0, "skills" : "Java" } /* 2 */ { "_id" : ObjectId("5d958cdc446a46c989b98887"), "name" : "Avinash", "age" : 27.0, "skills" : "MongoDB" } /* 3 */ { "_id" : ObjectId("5d958cdc446a46c989b98887"), "name" : "Avinash", "age" : 27.0, "skills" : "Node" } /* 4 */ { "_id" : ObjectId("5d958cdc446a46c989b98887"), "name" : "Avinash", "age" : 27.0, "skills" : "Angular" }
MongoDB $unwind Nested Array
Let’s insert one more document into products collection using the below code:
db.products.insertOne({ "name": "Test", "items": [{ "quantity": "10", "category": "test_cat", "images": [{ "name": "abc.PNG", "size": 98 }, { "name": "def.PNG", "size": 156 } ], "link": "http://url_of_link" }] })
We will use $unwind operator here on images, See the code below:
db.products.aggregate({ $project: { name: 1, items: 1 } }, [{ '$unwind': { 'path': '$items' } }, { '$unwind': { 'path': '$items.images' } }] )
Conclusion
In this tutorial, you have learned about MongoDB $unwind operator. I will suggest you to keep practicing each and every step carefully and you will be master in it.
I hope you liked this tutorial. Feel free to ask any doubt in the comment section below, I will be happy to resolve your queries.