

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Questions & Answers
- MongoDB aggregate to convert multiple documents into single document with an array?
- Add all records from one array to each record from a different array in JavaScript
- Aggregate multiple arrays into one huge array with MongoDB?
- How to create a new collection in MongoDB?
- Set server status to inactive in a MongoDB collection with server records?
- Convert Collection to Capped in MongoDB
- Match multiple criteria inside an array with MongoDB?
- Removing an array element from a MongoDB collection
- MongoDB query to find a specific city record from a collection
- MongoDB query to get record beginning with specific element from an array?
- How to match multiple criteria inside an array with MongoDB?
- Get the maximum mark records from a collection with documents in MongoDB
- Add new field to every document in a MongoDB collection?
- Deleting all records of a collection in MongoDB Shell?
- Combine multiple text records to one in MySQL
Advertisements