2

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?

1 Answers1

1

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'
  }})
})
sheilak
  • 5,833
  • 7
  • 34
  • 43
  • Oh, I see. I had expected Math.random to run once for each user. That makes sense. –  Jul 16 '15 at 23:12