MongoDB $unwind Operator – (Aggregation Stage)

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"
    ]
}
You can notice how “skills” is an array of 4 items, In our case, it is “Java”, “MongoDB”, “Node”, and “Angular”.
Now, let’s use $unwind operator and see how results look like.
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"
}
You can notice that the only changes in the result array are what is being returned in the value of the skills.
In the above result, we have all four skills in separate elements.

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'
        }
    }]
)
If you see the above code you will find, we have used $unwind two times in an array. It means if you have nested documents in your collection then you can use $unwind as an array.
For more details, you can see the MongoDB $unwind details guide here.

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.

Leave a Reply