Update Field Name

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 are doing the appropriate update.

But the error message says it all.

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.

1 Like

@M_ALI_N_A, it has been a week since I provided you with what I think is the correct solution.

It would be nice to have a followup. And if indeed, the issue was the one I mentioned, place mark my post as the solution.

Thanks in advance

1 Like

I’m sorry somehow i couldn’t see you answer. But thanks for answering i got it what you’re saying.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.