Reputation: 1
When I used numbers as keys, the compound index prefixes created were not as expected。
To define a compound index:
admin> use TestDB
TestDB> db.createCollection('coll')
TestDB> db.coll.createIndex({4:1,1:-1},{unique:true})
TestDB> db.coll.getIndexex()
Output
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { '1': -1, '4': 1 }, name: '1_-1_4_1', unique: true }
]
I expected 4 to be the prefix of the index, but it turned out to be 1, why? It looks like the sorting happens
And when I use strings as keywords, the results are completely inconsistent。
Following:
TestDB> db.createCollection("coll2")
TestDB> db.coll2.createIndex({'s':1, 'a':-1},{unique:true})
Output
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { s: 1, a: -1 }, name: 's_1_a_-1', unique: true }
]
What? It doesn't seem to be sorting.
Upvotes: 0
Views: 32
Reputation: 5065
According to this issue, which references the official specification, this is a result of how Javascript works.
For example, in Node:
$ node
Welcome to Node.js v16.17.0.
Type ".help" for more information.
> var pattern = { 4: 1, 1: -1 }
undefined
> pattern
{ '1': -1, '4': 1 }
You can see similar behavior in this jsfiddle.
If you are attempting to create indexes that have numeric keys, you will need to do so with a different language/driver.
Upvotes: 1