Search code examples
javascriptmongodbindexingmeteorcompound-index

Ensuring that Collection._ensureIndex passes fields in the right order


The mongo indexes documentation says that for compound indexes, the order of the fields is very important: the index can only support queries using any prefix of the fields: http://docs.mongodb.org/manual/core/indexes/

Meteor currently has a pass-through to MongoDB's ensureIndex as Collection._ensureIndex on the server side.

However, when passing arguments to Collection._ensureIndex in Javascript, these fields get turned into a Javascript object. Do we have any guarantee that Mongo will read them in the same order? If not, what's the right way to set up this index?

This may have to do with how JS objects are stored. Are they an associative array, or do they keep their properties in order?


Solution

  • Javascript does not specify the ordering of parameters on an object but V8 does so at least for node.js the parameters are always in the order they were added to the object.

    so if you do

    var a = {a:1, b:1, c:1}
    var keys = Object.keys(a)
    

    returns

    [ 'a', 'b', 'c' ]