Fluffy
Fluffy

Reputation: 28362

Are there any downsides of using a unique string instead of MongoId as an _id?

I have a user collection, obviously all logins are unique, and at this point I can't think of a reason not to use them instead of the default generated MongoId. Are there any downsides to this approach?

Upvotes: 1

Views: 64

Answers (2)

Tyler Brock
Tyler Brock

Reputation: 30136

Yeah that sounds perfectly ok. ObjectIds can be useful when doing sharding, provide a built in timestamp, and probably are more efficient for indexing, storage because they are all the same size. However, if it makes more sense for your application to use login then that should work just fine.

Upvotes: 1

Russell
Russell

Reputation: 12439

If your logins are also email addresses, as they often are, at some point your users will change their email address which will cause you problems if you've used it as the _id. Even if you don't use email addresses for logins you may still want to allow users to change their username.

But the question I would ask, instead of are there any downsides to using login as _id, is: are there any downsides to just using the standard ObjectId field? What do you hope to gain by using login instead?

As Tyler Brock points out in his answer, using ObjectId gives you some added benefits, as there is some extra information encoded in an ObjectId such as a timestamp and an identifier of the instance of MongoDB that created the document. Might come in useful someday.

In my experience, unless and sometimes even if there's a really good reason to do otherwise, it's usually better to go with the flow of whatever technology you're using.

Upvotes: 0

Related Questions