I'd like to build an index that supports queries against specific array element positions.
Given several million documents with arrays of values:
db.foo.insert({ array: [true, false, null, true] })
db.foo.insert({ array: [false, null, true, true] })
I'd like to search for documents with true
in position 2.
db.foo.find({ "array.2": true })
If I create a multikey index:
db.foo.createIndex({ array: 1 })
The index supports queries of the form { "array": true }
(searching all array elements) but not { "array.2": true }
(searching a specific array element).
The documentation says "MongoDB creates an index key for each element in the array", so I was expecting that if I created an index on the array
field, it would be used for queries on array.0
, array.1
, array.2
, etc. Is there a trick to getting this to work?