我对mongodb中的复合索引创建有疑问: 假设我想创建这个复合索引:
cSchema.index({account:1, authorization: 1, c_type: 1});
问题是,javascript不保证字典顺序,所以我不确定复合索引是否符合我想要的顺序。
如何确保按照该顺序确实{account:1, authorization:1, c_type:1}
?
谢谢!
答案 0 :(得分:3)
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.
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.
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.