
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make an Array of Multiple Arrays in MongoDB
To make an array of multiple arrays, use $unwind in MongoDB aggregate. Let us create a collection with documents −
> db.demo289.insertOne({"Section":["A","B","E"],"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4c06fcf49383b52759cbc3") } > db.demo289.insertOne({"Section":["C","D","B"],"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4c070af49383b52759cbc4") }
Display all documents from a collection with the help of find() method −
> db.demo289.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : [ "A", "B", "E" ], "Name" : "Chris" } { "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : [ "C", "D", "B" ], "Name" : "David" }
Following is the query to make a single array of multiple arrays in MongoDB −
> db.demo289.aggregate({ $unwind : "$Section" } );
This will produce the following output −
{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "A", "Name" : "Chris" } { "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "B", "Name" : "Chris" } { "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "E", "Name" : "Chris" } { "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "C", "Name" : "David" } { "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "D", "Name" : "David" } { "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "B", "Name" : "David" }
Advertisements