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" : "[email protected]" } { "_id" : ObjectId("5e8f490654b4472ed3e8e86d"), "EmailId" : "[email protected]" } { "_id" : ObjectId("5e8f490a54b4472ed3e8e86e"), "EmailId" : "[email protected]" }