There is this question which asks essentially the same question but is three questions in one and the 1/3 I'm after isn't really answered very well so I'm asking it again:
I'm starting an new MongoDB project (in NodeJS). For the required document _id
field I'm considering using the string serialization of an ObjectId
instead of MongoDB's default ObjectId
(i.e. setting { _id: String(mongodb.ObjectId()), ...}
instead of inbuilt default). Tell me why shouldn't I do this?
In general the argument for, is it makes comparisons easier:
- If I grab an object identifier off the wire or out of some JSON document, I don't need to hydrate it into an ObjectId before doing comparison queries in a find or aggregation pipeline. And I don't need to know a priori a given field is an ObjectId and special case it.
- It saves confusing about comparison in code if object identifiers are just always a strings. For example in NodeJS
<ObjectId> === <String>
is always false you have to useObjectId.equals
or==
.
I gather there was a very good reason MongoDB decided to use ObjectId over just strings. I mean sure, I can see some potential advantages but I never understood or found any clear documentation outlining why they did this.
ObjectId
as string. Another rather common misuse is to storeDate
values as string - it's a design flaw and sooner or later it will create trouble.ObjectId
has always 12 bytes, string "63808b1c4d9cd4c7c184f40f" has 24 bytes and in general it can have any length and any character (not just hex symbols). The CPU can handle raw bit values more efficient than text strings. Strings in MongoDB are stored as UTF-8, which decoding is complex, because UTF-8 is a multi-byte characters set. Apart from that, nobody forces you to useObjectId
. You just need a unique_id
value, in general the format/datatype is arbitrary.