Convert an array of objects to individual documents and save in the db

I have a collection which has data like

{
    projectId:'abc',
    goals:[{name:'a',age:5},{name:'b',age:9}]
}

Is it possible to make a query that will convert the array of objects goals
to documents like

{
    _id:'id'
    name:'a',
    age:5
},

{
    _id:'id'
    name:'b',
    age:9
}

Hi @AbdulRahman_Riyaz ,

Its possible to use unwind and regenerate an _id for every document:

db.collection.aggregate([{$unwind : { path : "$goals"}}},
{ $replaceRoot: { newRoot: "$goals" } },
{ $out : "newCollection"}

This code have not been tested but thats the idea.

Ty
Pavel

1 Like

Thanks, Pavel for taking the time to answer.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.