user773737
user773737

Reputation:

Randomizing unique data with mongo?

I'm trying to scramble all the email properties in my db. email is defined in the Mongoose model as unique. Here's the script I'm attempting to run in the shell

db.getCollection('users').update(
  {},
  {$set{
    email:'sanitized'+Math.random()*100000000000000000+'@'+Math.random()*100000000000000000+'.com'
  }},
  {multi:true}
)

I'm trying this:

But it comes back with an error:

duplicate key error index: test.users.$email_1 dup key

I realize that Math.random() isn't perfect, but this command has never updated more than the first document in the collection.

How can I do what I want to do?

Upvotes: 2

Views: 192

Answers (1)

sheilak
sheilak

Reputation: 5873

The Math.random functions are executing once each client-side and then this one constant email value is being passed into the update function.

If there was not a unique index on email, every User in the database would be set to the same email.

You could do individual updates like this:

db.getCollection('users').find().forEach(function(u){
  db.users.update({_id : u._id}, {$set:{
    email:'sanitized'+Math.random()*100000000000000000+'@'+Math.random()*100000000000000000+'.com'
  }})
})

Upvotes: 1

Related Questions