How to index two arrays in MongoDB?

db.hello.ensureIndex({"array1":1, "array2":1}) 

MongoDB does not allow this because they say that "it can get out of hand." However, I know that my arrays will never exceed the length of 3. How can I hack MongoDB to index multiple arrays at once?

When using a composite index, at most one of the indexed values ​​in any document can be an array. Therefore, if we have an index on {a: 1, b: 1}, the following documents are both good:

{a: [1, 2], b: 1} {a: 1, b: [1, 2]} However, this document cannot be inserted with the error message "parallel arrays cannot be indexed":

{a: [1, 2], b: [1, 2]} The problem with indexing parallel arrays is that each value in the Cartesian product must have composite keys indexed, which can get out of hand very quickly.

+9
source share
1 answer

A short answer to your question: you are not the only option available - to store each unique pair as a single element of the array. So instead of:

 {a:[1,2], b:[8,9]} 

you store

 {ab:[[1,8], [1,9], [2,8], [2,9]]} 

Obviously, this has several drawbacks, so it really depends on your specific use case, whether this is a suitable workaround. However, I agree that Mongo should not reject multiple array indices just to protect against idiots. This is a good feature for small / low power arrays.

+5
source

Source: https://habr.com/ru/post/891614/


All Articles