I want to update field names in all the documents and I am using this query. But it only updates first document.
db.users.updateMany(
{ “username”: { $exists: true } }, // Filter to only documents that have the old field
{ $rename: { “username”: “email” } }
);
Then i run again, following error is there:
E11000 duplicate key error collection: test.users index: username_1 dup key: { username: null }
Is there anyway to update a fieldname in all the documents in a database?
You have a unique index on the username field. When you rename username to email, you get null as the value of the username (because the field does not exist anymore). Hence, you get duplicate key error.
For you update to work, you must remove the unique index username_1. You most likely need to create one for email.