Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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.
Advertisements
