Skip to content

Comment on MongoDB Gotchas and How To Avoid Them

Comments

Here's two:

(1) There's no need to add a "created" field on your documents. You can extract it from the _id field by just taking the first 4 bytes.

(2) If you are storing hashes (md5 for example), you might want to consider storing them as BinData instead of strings. Mongo uses UTF-8 so every character will be at least 8 bits whereas you can get away with 4 bits per character.

ukd1OP

Great points but they are not really gotchas; I was trying to help people avoid big / 'obvious' / documented things when using MongoDB :-)

Sure :)

Can you efficiently select and sort on the date part of the _id?

Sorting is easy, you just choose _id as the sort field.

Selecting is also reasonably easy, the first 4 bytes of the id are the timestamp (seconds since the epoch). You just create a hex string in that format -- 4 bytes of timestamp and then 8 bytes of zeroes and then create an object ID (using the classes provided by your driver) and do:

    coll.find({_id:{$gte:<id>}})
or whatever is the equivalent in your language of choice.
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.