Home > other >  Is it efficient to store sha256 hash of username in _id field in MongoDB?
Is it efficient to store sha256 hash of username in _id field in MongoDB?

Time:04-05

I have a special need to hash the username, and also I need to keep the usernames unique for my purpose. So, my question is can I override default '_id' field of mongoDB with sha256 hash of username? I read that _id needs to be unique and already indexed, so why would I want to create another entry instead of storing in _id.

Does this cause any technical problems which I'm unaware of? Is it efficient when searching _id as it is indexed?

This application is a Flask application using Flask-pymongo as mongo driver and helper.

By default:

_id : ObjectId(...)

I need:

_id : sha256(username)

Please explain if there are any issues with this approach.

CodePudding user response:

Technically, there is no problem with using sha256 for the value of _id. The default ObjectId type in MongoDB is convenient for creating a unique value "on the spot" but not required. The bit pattern in _id has to be unique, that's all.

From a data design perspective, if you use a function on user data (e.g. sha256) to create material that is linked to the physical DB mechanics (like _id) you must make sure that the user data does not change over the lifetime of the data. In this case, username may be OK but email address for example might be poor because a user could change their email address.

  • Related