Search code examples
mongodbuniqueidentifierunique-index

email as _id in a MongoDB user collection


I have a user collection in a MongoDB. The _id is currently the standard MongoDB generated ObjectId. I also have a unique key constraint against a required 'email' field. This seems like a waste.

Is there any reason why I should not ditch the 'email' field and make that data the _id field?


Solution

  • I have read Neil's answer and I partially agree with it (also I am really skeptical about 'significant performance gains'). One thing I have not found in your question is 'what are you going to do with this email'. Are you going to search by it or it is just saved there? And one of the most important things which was not addressed in previous answer: is it going to be changed?

    It is not uncommon that people who would use your system will be going to change their email (lost / is not used anymore). If you will put your _id as their email you will not be able to change it easily (you can not modify _id in mongo). You will need to copy, remove add new element in this case (which will not be atomic).

    So I would put this as one big reason not to do so. But you need to decide whether you will allow people to change email addresses.