What is the $unwind operator in MongoDB?


The $unwind operator in MongoDB is the same for each array, it returns the mapping document. Here is the demo of $unwind operator in MongoDB.

To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.unwindOperatorDemo.insertOne({"StudentName":"Larry","StudentAge":23,"StudentSubje
ct":["C","C++","Java","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7ef5f3559dd2396bcfbfc8")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.unwindOperatorDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c7ef5f3559dd2396bcfbfc8"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentSubject" : [
      "C",
      "C++",
      "Java",
      "MongoDB"
   ]
}

Here is the demo of $unwind operator. The query is as follows −

> db.unwindOperatorDemo.aggregate(
   ... { $project : {
      ... StudentName : 1 ,
      ... StudentAge: 1 ,
      ... StudentSubject : 1
   ... }},
   ... { $unwind : "$StudentSubject" }
... ).pretty();

The following is the output −

{
   "_id" : ObjectId("5c7ef5f3559dd2396bcfbfc8"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentSubject" : "C"
}
{
   "_id" : ObjectId("5c7ef5f3559dd2396bcfbfc8"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentSubject" : "C++"
}
{
   "_id" : ObjectId("5c7ef5f3559dd2396bcfbfc8"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentSubject" : "Java"
}
{
   "_id" : ObjectId("5c7ef5f3559dd2396bcfbfc8"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentSubject" : "MongoDB"
}

Look at the sample output, the fields “StudentName” and “StudentAge” are mapping to each “StudentSubject” array field.

Updated on: 30-Jul-2019

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements