[MongoDB]: For loop to generate documents with array, sub and nested documents

Find below sample for loop to generate a document with array, sub-document, nested-document

use mydb
db.studentscol.drop()

for(var i = 1; i <= 1000 ; i++){var r= Math.random().toString(36).substring(7); db.studentscol.insert(
{ _id:i,
name:r,
address: { address_id:i, state:r,country:”India”,street:{name:r,colony:{ name:r,pin:r}}},
hobbies: [{h1:r},{h2:r},{h3:r},{h4:r}]
});}

// If you need a unique name for all the fields above, replace r with Math.random().toString(36).substring(7) everywhere in the above for loop.

> use mydb
switched to db mydb
> db.studentscol.drop()
true
> for(var i = 1; i <= 1000 ; i++){var r= Math.random().toString(36).substring(7); db.studentscol.insert(
… { _id:i,
… name:r,
… address: { address_id:i, state:r,country:”India”,street:{name:r,colony:{ name:r,pin:r}}},
… hobbies: [{h1:r},{h2:r},{h3:r},{h4:r}]
… });}
WriteResult({ “nInserted” : 1 })
>
> db.studentscol.findOne()
{
“_id” : 1,
“name” : “23ul1l”,
“address” : {
“address_id” : 1,
“state” : “23ul1l”,
“country” : “India”,
“street” : {
“name” : “23ul1l”,
“colony” : {
“name” : “23ul1l”,
“pin” : “23ul1l”
}
}
},
“hobbies” : [
{
“h1” : “23ul1l”
},
{
“h2” : “23ul1l”
},
{
“h3” : “23ul1l”
},
{
“h4” : “23ul1l”
}
]
}
>

  • Ask Question