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" }

Updated on: 01-Jul-2020

410 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements