Why is `.sort()` method used with a nested array? Ex: .sort([[ 'year', 1 ]])

In the Cursor Methods and Aggregation Equivalents lecture video in Chapter 2, we look through the cursor-methods-agg-equivalents.spec.js file to find various examples.

In these examples, whenever the .sort() method is used, it is used with a double (nested) array. Ex: .sort([[ 'year', 1 ]]).

Why is this? The documentation for cursor.sort() suggests it should use an object instead. Ex: .sort({'year', 1 }).

Any clarification on this would be appreciated!

The documentation you should be looking at here is actually the Node Driver implementation of sort(), not that the difference is obvious but it is in fact there in the function parameters:

keyOrList	string | array | object	//The key or keys set for the sort.

So in fact there are three valid ways to supply this for the Node dirver.

The documentation you referenced is really only for the mongo “shell” methods, though usually these are basically the same across drivers, but there often are some differences.

The Why?, is simply because of the fact that an object does not guarantee the order of keys, which is generally true of the official spec but mostly in real JavaScript engine implementations they try not to mess around with the supplied order of object keys just to keep the world at large happy!

Some language implementations ( notably Python, Perl ) have special forms of such Object structures ( which they call their own things of course ) which maintain an order of insertion for “keys” even though they (sort of) appear to look the same on the surface.

JavaScript does not have that ( neither does BSON really, but digressing…). So the way you maintain order with a JavaScript data structure it with an Array. Thus an array of “key value pairs” i.e:

{ joe: 1, smith: 1 }

// Is the same as, but with guaranteed order

[ [ 'joe', 1 ], [ 'smith', 1 ] ]

Should be a bit clearer with more than one value.

But really Why? - Because the order of keys is important when you are issuing a .sort() or a createIndex() for that matter. So to make sure that these instructions are always constructed and transported in the correct order we use an Array instead of plain Object notation.


Thank you naillunn, that’s a very clear explanation!

It’s not totally clear, even from the Node Driver documentation, that nesting arrays will preserve that index order when executing the sorts. But that is a very handy thing to know, and I’m glad I was able to learn it from you!