Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose compound index creation fields order

I have a question regarding compound index creation in mongodb: Say I want to create this compound index:

cSchema.index({account:1, authorization: 1, c_type: 1});

Problem is, javascript doesn't guarantee dictionary order, so I won't be sure the compound index is in the order I want.

How can I make sure it's indeed {account:1, authorization:1, c_type:1} in that order ?

Thanks !

like image 912
Harel Rozental Avatar asked Apr 09 '17 15:04

Harel Rozental


1 Answers

The simple answer is that most abuse the behaviour that simple String properties that don't parse to an integer on an Object will enumerate in creation order. Although not guaranteed in ES2015 for some enumeration methods, it does work in a confined environment like Node/V8. This has worked in most JS engines for a while now but had never been part of the ES spec before ES2015.

MongoDB

The underlying MongoDB driver createIndex function supports String, Array and Object index definitions. The parsing code is in a util function called parseIndexOptions.

If you specify an array of Strings, Array pairs, or Objects then the order will be fixed:

['location','type']
[['location', '2d'],['type', 1]]
[{location: '2d'},{type: 1}]

Also note that the createIndex code does use Object.keys to enumerate when it gets an Object of index properties.

Mongoose

The Schema#index function is documented as requiring an Object to pass to "MongoDB driver's createIndex() function" so looks to support passing through whatever options you provide.

There are a couple of places where indexes are further processed though. For example when you create a sub document with an index, the index needs to have the parent schema prefixed onto field names. On a quick glance I think this code still works with an Array but I can't see any tests for that in the Mongoose code so you might want to confirm it yourself.

Mongoose does have a compound index test that relies on Object property order.

like image 69
Matt Avatar answered Sep 29 '22 10:09

Matt