- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split a document by its subdocuments in MongoDB
To split a document by its subdocuments, use $unwind in MongoDB. Let us create a collection with documents −
> db.demo276.insertOne({"Name":"Chris","Subjects":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e48f953dd099650a5401a51") }
Display all documents from a collection with the help of find() method −
> db.demo276.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e48f953dd099650a5401a51"), "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB" ] }
Following is the query to split a document by its subdocuments −
> db.demo276.aggregate( [ { $unwind : "$Subjects" } ] )
This will produce the following output −
{ "_id" : ObjectId("5e48f953dd099650a5401a51"), "Name" : "Chris", "Subjects" : "MySQL" } { "_id" : ObjectId("5e48f953dd099650a5401a51"), "Name" : "Chris", "Subjects" : "MongoDB" }
Advertisements