Is it OK to store Mongo _id as a string, instead of ObjectId

Viewed 842

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:

  1. Store _id as an ObjectId in the DB.
  2. Store _id as 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 ObjectId objects for every write operation. I suspect having to add a loop on the app server to parse incoming data and convert strings to new ObjectId(item._id) for the million records would level the results.
  • Using ObjectId is 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.

1 Answers

The ObjectID type has a built-in timestamp for sorting. Four bytes of the 12 bytes you reference are dedicated to representing the time since the unix epoch in seconds. When you create ObjectIDs they are sortable with each other automatically based on the order in which they were created.

You can use the .getTimeStamp() function on your ObjectID to return the timestamp.

var id = new ObjectId();
console.log(id.getTimestamp())

You may think you're saving some infrastructure costs on the storage of your documents, but there is also savings in the overhead when it comes to accessing, sorting, and indexing as well.

Related