Randomizing unique data with MongoDB and placing values for emailid with wordnJohn in the beginning

To randomize unique data with MongoDB and generate email addresses starting with "John", use Math.random() within JavaScript functions to create unique values for each document.

Syntax

db.collection.find().forEach(function(doc){
    db.collection.update(
        {_id : doc._id}, 
        {$set: {EmailId: 'John' + Math.random() * multiplier + '@domain.com'}}
    )
})

Sample Data

First, create a collection with null EmailId fields ?

db.demo561.insertMany([
    {EmailId: null},
    {EmailId: null},
    {EmailId: null}
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5e8f490454b4472ed3e8e86c"),
        ObjectId("5e8f490654b4472ed3e8e86d"),
        ObjectId("5e8f490a54b4472ed3e8e86e")
    ]
}

Display the initial documents ?

db.demo561.find();
{ "_id" : ObjectId("5e8f490454b4472ed3e8e86c"), "EmailId" : null }
{ "_id" : ObjectId("5e8f490654b4472ed3e8e86d"), "EmailId" : null }
{ "_id" : ObjectId("5e8f490a54b4472ed3e8e86e"), "EmailId" : null }

Example: Generate Random Email Addresses

Use forEach() to iterate through documents and update each with a unique randomized email ?

db.demo561.find().forEach(function(doc){
    db.demo561.update({_id : doc._id}, {$set:{
        EmailId: 'John' + Math.random() * 100000000000000000 + '@' + Math.random() * 100000000000000000 + '.com'
    }})
})

Verify the randomized email addresses ?

db.demo561.find();
{ "_id" : ObjectId("5e8f490454b4472ed3e8e86c"), "EmailId" : "John23607829153155868@62688631475897960.com" }
{ "_id" : ObjectId("5e8f490654b4472ed3e8e86d"), "EmailId" : "John63351292234094710@79460595429439740.com" }
{ "_id" : ObjectId("5e8f490a54b4472ed3e8e86e"), "EmailId" : "John71315584787457890@99884571221675000.com" }

Key Points

  • Math.random() generates numbers between 0 and 1; multiply by a large number for unique values.
  • forEach() iterates through each document to apply individual updates.
  • Each email starts with "John" followed by randomized numeric values for uniqueness.

Conclusion

Use Math.random() with forEach() to generate unique randomized data in MongoDB. This approach ensures each document gets a distinct value while maintaining the desired prefix pattern.

Updated on: 2026-03-15T03:35:00+05:30

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements