Semicolon
Semicolon

Reputation: 7413

MongoDB multiple sort properties: How is precedence determined?

According to Mongo's docs, you can specify multiple sort keys like this:

{ $sort : { age : -1, posts: 1 } }

Which they say will sort first by age (descending) then by posts (ascending).

But the sort query is a Javascript object. To the best of my knowledge, although implementations typically iterate over properties in the order they were created, that's not actually part of ECMAScript's spec: object properties officially have no order.

Is MongoDB really relying on arbitrary behavior that could vary by implementation, am I wrong about the ECMAScript spec, or am I missing something in the Mongo docs that lets you tune the precedence some other way?

Upvotes: 1

Views: 321

Answers (2)

Sammaye
Sammaye

Reputation: 43884

The console is special, its objects are actually ordered unlike normal EMCAscript so that this can happen.

Here is a linked question from a 10gen employee that states: https://stackoverflow.com/a/18514551/383478

Among other things, order of fields is always preserved.

N.B: It is good to note that V8 (runs MongoDB shell and MR since v2.2 about) has ordered objects in practice anyway.

The only true way in non-V8 JS to keep order is to do key lookups like: How to keep an Javascript object/array ordered while also maintaining key lookups?

Upvotes: 1

Neil Lunn
Neil Lunn

Reputation: 151092

Yes you are wrong about the ECMAScript spec. Properties retain their order which is why with some drivers for languages ( e.g Perl orders "hashes" by key name by default, use Tie::IxHash to change that) recommend forms that also maintain an order in the structure to be converted.

At any rate, this is not "really" JavaScript anyhow, but it is BSON. It is borrowed behavior anyhow so the statement really remains the same. The order you specify is preserved.

Upvotes: 1

Related Questions