To randomize unique data, use Math.random() in MongoDB. Let us create a collection with documents −
> db.demo561.insertOne({EmailId:null});{
"acknowledged" : true, "insertedId" : ObjectId("5e8f490454b4472ed3e8e86c")
}
> db.demo561.insertOne({EmailId:null});{
"acknowledged" : true, "insertedId" : ObjectId("5e8f490654b4472ed3e8e86d")
}
> db.demo561.insertOne({EmailId:null});{
"acknowledged" : true, "insertedId" : ObjectId("5e8f490a54b4472ed3e8e86e")
}Display all documents from a collection with the help of find() method −
> db.demo561.find();
This will produce the following output −
{ "_id" : ObjectId("5e8f490454b4472ed3e8e86c"), "EmailId" : null }
{ "_id" : ObjectId("5e8f490654b4472ed3e8e86d"), "EmailId" : null }
{ "_id" : ObjectId("5e8f490a54b4472ed3e8e86e"), "EmailId" : null }Following is the query for randomizing unique data with MongoDB −
> db.demo561.find().forEach(function(doc){
... db.demo561.update({_id : doc._id}, {$set:{
... EmailId:'John'+Math.random()*100000000000000000+'@'+Math.random()*100000000000000000+'.com'
... }})
... })Display all documents from a collection with the help of find() method −
> db.demo561.find();
This will produce the following output −
{ "_id" : ObjectId("5e8f490454b4472ed3e8e86c"), "EmailId" : "John23607829153155868@62688631475897960.com" }
{ "_id" : ObjectId("5e8f490654b4472ed3e8e86d"), "EmailId" : "John63351292234094710@79460595429439740.com" }
{ "_id" : ObjectId("5e8f490a54b4472ed3e8e86e"), "EmailId" : "John71315584787457890@99884571221675000.com" }