Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I index two arrays in MongoDB?

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

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

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

{a: [1, 2], b: 1} {a: 1, b: [1, 2]} This document, however, will fail to be inserted, with an error message "cannot index parallel arrays":

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

like image 616
TIMEX Avatar asked Jun 29 '11 06:06

TIMEX


People also ask

Can we index array in MongoDB?

To index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that hold both scalar values [1] (e.g. strings, numbers) and nested documents.

Can MongoDB use multiple indexes?

MongoDB can use the intersection of multiple indexes to fulfill queries. In general, each index intersection involves two indexes; however, MongoDB can employ multiple/nested index intersections to resolve a query.

Which is the index used for multiple fields in MongoDB?

MongoDB also supports user-defined indexes on multiple fields, i.e. compound indexes. The order of fields listed in a compound index has significance. For instance, if a compound index consists of { userid: 1, score: -1 } , the index sorts first by userid and then, within each userid value, sorts by score .

Where is array index in MongoDB?

Starting from MongoDB version 3.4 we can use the $indexOfArray operator to return the index at which a given element can be found in the array. $indexOfArray takes three arguments. The first is the name of the array field prefixed with $ sign.


1 Answers

The short answer to your question is; you don't. The only option available to you is to store the every unique pair as a single array element. So rather than :

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

you store

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

Obviously this has a few downsides so it really depends on your specific usecase whether or not this is an appropriate workaround. I do agree however that mongo shouldn't reject multiple array indexes just for idiot proofing. It's a good feature for small/low cardinality arrays.

like image 114
Remon van Vliet Avatar answered Oct 11 '22 21:10

Remon van Vliet