Jeremy W. Sherman

stay a while, and listen

Key Reordering: MongoDB's Achilles' Heel

MongoDB relies on key order but doesn’t guarantee it will preserve document key order. Steer clear.

MongoDB document keys are ordered. Subdocument queries fail to retrieve results whose keys are in a different order. Indexing only works with keys in the same order.

This uglies up the client application interface. Languages regularly provide literal syntax for unordered associative arrays (aka hashes, maps, dictionaries). To guarantee all similar documents have the same key order, you either forgo the literal syntax provided by your language to use an order-preserving data structure, or you throw a sorting layer in between the application and MongoDB.

That’s bad, but you can work around it.

What you can’t work around is MongoDB rearranging keys behind your back:

When performing update operations that increase the document size beyond the allocated space for that document, the update operation relocates the document on disk and may reorder the document fields depending on the type of update. (Update - MongoDB Manual 2.4.2)

Let’s read that again: “[T]he update operation […] may reorder the document fields.”

Just dandy.

Using MongoDB requires a fixed key order for reliable operation, but MongoDB fails to preserve key order. As convenient and simple as MongoDB is, this is enough for me to advise anyone: Stay well away from MongoDB.