1

I know keys order are not guaranteed in JS objects.

In the MongoDB Node.JS Driver I want to generate the $sort stage of the aggregation framework within a function and return an object to be piped: (e.g. { $sort: { field1: -1, field2: 1 } }).

const obj = [
  ['field1', 1],
  ['field2', -1]
]

function sortFunc (obj) {
  return obj.reduce((acc, x) => {
    acc[x[0]] = x[1]
    return acc
  }, {})
}

// => { $sort: sortFunc(obj) } => { $sort: { field1: 1, field2: -1 } }

How to be sure sortFunc(obj) will preserve order and will not return { $sort: { field2: -1, field1: 1 } } to the pipe?

eakl
  • 91
  • 11
  • See if this helps you. http://stackoverflow.com/questions/41850572/how-is-order-of-properties-maintained-for-sort-in-mongodb – s7vr Apr 20 '17 at 00:14
  • Thanks Veeram. It's not very clear as it says the V8 implementation do preserve the key order but the MongoDB Node driver does not recommend to rely on it. Instead it proposes to pass an option object in .find({}, opt) but does not mention the aggregation framework. Finally it says the order is preserved when passed directly in the MongoDB shell thanks to BSON but my concerne is how the function return the object. I'm not very confortable with relying on V8 as it's not very portable... – eakl Apr 20 '17 at 00:36

0 Answers0