david_adler
david_adler

Reputation: 10942

How does mongo retain order of an object when defining an index?

From the mongodb docs

The order of the fields listed in a compound index is important. The index will contain references to documents sorted first by the values of the item field and, within each value of the item field, sorted by values of the stock field. See Sort Order for more information.

Docs link

But in javascript you can't depend on the order of keys in an object 😱. So how does mongo reliably preserve the order of item and stock in the above example of a compound index?

Upvotes: 2

Views: 231

Answers (1)

Thava
Thava

Reputation: 1665

No idea what the folks at MongoDB were smoking when they defined this API. As you have rightly pointed out, the JavaScript object only represents the unordered collection of key-value pairs both by design and spirit. For ordered collection, one could use array of objects.

The recent versions of JavaScript specifications encourage preserving the creation order of keys in the object for Object.keys and such methods. As others pointed out in the comments, relying on creation order of properties for the Object parameter for an API is plain stupid. It becomes even muddier if the object is cloned, the cloning library maintains the order or not. But probably it works since recent implementations now a days honors creation order and they pass the constant object inline.

Upvotes: 1

Related Questions