Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use a mongo ObjectId as a user's id?

Tags:

mongodb

Seeing as this value is unique and present for all users in a mongo database, are there any particular caveats to using this as a user identifier in a web application?

Particular issues I may be considering include if in the future the users need to be transferred.

like image 263
arcyqwerty Avatar asked Jul 28 '12 02:07

arcyqwerty


People also ask

Should you use MongoDB ObjectId?

Is it ok to use Mongo's “Object ID” as its unique identifier? Yes, it is intended for this purpose. Making unique IDs can be a pain in sharded environments, so MongoDB does this for you.

Is it okay to expose MongoDB ID?

No matter if it's MongoDb, SQL or any other id. Id is the key to data. If this key is only thing you need to view content that you should not - that's an issue.

Is MongoDB ObjectId UUID?

Overview. By default, the MongoDB Java driver generates IDs of the type ObjectId. Sometimes, we may want to use another type of data as the unique identifier of an object, such as a UUID. However, the MongoDB Java driver can't generate UUIDs automatically.

Do you need IDs in MongoDB?

All documents in MongoDB must have a populated _id field. If a document hasn't been assigned an _id value, MongoDB will automatically generate one.


1 Answers

... are there any particular caveats to using this as a user identifier in a web application?

A few that I've seen:

  1. It's not great for URLs. Twitter gives me a URL like http://twitter.com/gatesvp, with an ObjectId you get a url like http://example.com/ab12ab12ab12ab12ab12ab12.
  2. The ObjectId shards very poorly. It's not really random, it's somewhat sequential, so new users will cluster on shards rather than distribute randomly.
  3. You often need another unique identifier. Most websites have a requirement for unique e-mail or unique user name. Yes you can create a unique index on the "user name", but then you have two unique indexes, one that's useful and one that's just a random number.
  4. You will be referencing this everywhere. Your users' data will typically be spread across multiple collections all with a pointer to the "userId". Having ObjectIds (or Guids), means that you are constantly copy-pasting these big IDs everywhere and storing them in the DB.

Particular issues I may be considering include if in the future the users need to be transferred.

Transferred to where? Once you start storing user's data in MongoDB, the IDs are going to be the least of your problems transferring to another DB. All modern DBs can handle some form of String or Binary as the primary key ID, so your transfer should work just fine. But most of the complexity will have nothing to do with the ID.

like image 65
Gates VP Avatar answered Sep 19 '22 12:09

Gates VP