This question has been asked a few times, but none of the 'pros' for using ObjectId seem to apply to my case, and the questions are all quite old. I'm wondering if there's anything I'm missing.
Specifically, I'm deciding between these two options:
- Store
_idas anObjectIdin the DB. - Store
_idas the string representation of an ObjectId in the DB.
My understanding of the reasons to favour storing an ObjectId object over its string representation:
- They're 12 bytes instead of 24. This is only 12 MB per million records, a tiny fraction of the document size, and a few cents of extra infrastructure, so doesn't warrant adding complexity to my application code.
- They're 'faster'. I keep hearing this, but no one says how much faster, which makes me wonder if there's no difference and everyone just repeats what they heard from someone else. I found these benchmarks, where read times for single items are identical. There's differences when writing a million records, but I won't be doing that. Also benchmarks like this aren't taking into account the extra time taken to convert an object (coming over the network) from string IDs to
ObjectIdobjects for every write operation. I suspect having to add a loop on the app server to parse incoming data and convert strings tonew ObjectId(item._id)for the million records would level the results. - Using
ObjectIdis the 'normal' way to do it. I'm somewhat swayed by this argument, I don't like doing things the weird way. But as it results in extra code that's prone to bugs, it's not a good enough reason on its own.
The reason for wanting to do option 2 is that I'm converting to/from string/ObjectId in many places in my app as data flows between userland and the DB. Not just for _id fields, but for otherItemId and listOfRelatedThingIds. They all get implicitly converted to strings on the way out (over the network) and need to manually be converted back on the way in. It's not the worst thing in the world, but if there's no good reason to be doing it, then I'll switch to strings in the DB.