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
MongoDB Convert One record with an array to multiple records in a new collection?
For this, you can use $out along with aggregate() and $unwind. Let us create a collection with documents −
> db.demo757.insertOne(
... {
... "id": 101,
... "Name": ["John", "Bob", "Chris"]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eb025745637cd592b2a4ae2")
}
> db.demo757.insertOne(
... {
... "id": 102,
... "Name": ["David"]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eb025755637cd592b2a4ae3")
}
Display all documents from a collection with the help of find() method −
> db.demo757.find();
This will produce the following output −
{ "_id" : ObjectId("5eb025745637cd592b2a4ae2"), "id" : 101, "Name" : [ "John", "Bob", "Chris" ] }
{ "_id" : ObjectId("5eb025755637cd592b2a4ae3"), "id" : 102, "Name" : [ "David" ] }
Following is the query to convert one record with an array to multiple records in a new collection −
> db.demo757.aggregate([
... {$unwind: '$Name'},
... {$project: {_id: 0}},
... {$out: 'demo758'}
... ])
> db.demo758.find();
This will produce the following output −
{ "_id" : ObjectId("5eb02582192bedc4738b5881"), "id" : 101, "Name" : "John" }
{ "_id" : ObjectId("5eb02582192bedc4738b5882"), "id" : 101, "Name" : "Bob" }
{ "_id" : ObjectId("5eb02582192bedc4738b5883"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5eb02582192bedc4738b5884"), "id" : 102, "Name" : "David" }Advertisements