Can we specify $sort in an array for example to ensure that fields are sorted in the desired order?
Also of concern, the doc instructions is not necessarily true for the shell either as evidenced by this open bug from 2013: https://jira.mongodb.org/browse/SERVER-11358 (which is still the case when tested on mongo 4.2.6)
Most languages provide an order-preserving data type which can be used as an alternative (for example, Map in modern versions of Node.js). Official MongoDB drivers include a helper class if there isn’t a native data type, such as the SON class in the Python driver).
However, I strongly recommend avoiding numeric key names as this is both a straightforward workaround for this issue and avoids some syntactic ambiguity between array references and embedded fields. Using dot notation, a reference like data.2 could either be referring to the 3rd element in the 0-based data array or a field 2 embedded within data . Using numeric field names may also result in unexpected outcomes (such as backfilling an array) with the right combination of update syntax and documents.
Thanks for that quick reply, so if I’m understanding you correctly here, you are suggesting for node, we use a Map object rather than a plain old JS object? for example something like the below to ensure “a” gets sorted before “10” in case of some strange JS run time:
I totally understand what you’re saying regarding using alphanumeric rather than numeric field names and we’re currently using meaningful alpha field names. I was just made aware that in the ES standard, it didn’t necessarily dictate any specific order for the enumeration of properties of objects, so I just wanted to be prepared for backup options in case the current V8 engine behavior changes and this has been very helpful for that! I’m glad to know that the driver supports the order-preserving Map data structure in case V8 behavior changes in the future.