Roman Klimenko
DA

Using objects as _id in MongoDB

MongoDB

Using objects as _id fields in MongoDB can be risky. This detail deserves a warning in bold red text, but it is easy to overlook in the official documentation:

"Unlike JavaScript objects, the fields in a BSON document are ordered."

This means you can accidentally have both { _id: { name: "Launchpad", surname: "McQuack" } } and { _id: { surname: "McQuack", name: "Launchpad" } } in the same collection.

I've encountered this issue only once in production code, fortunately many years ago. I still see objects used as identifiers, though, and the same problem appears when an object is hashed without sorting its properties. That's why I wrote this short post.