Con MongoDB, ¿cuáles son los campos que deben seleccionarse para crear índices?

If there is a query that filters on field a and b and then order on c, do I need to build separate indexes for a, b, and c, or should I actually build a compound index of (a, b, c)? And also, does the should the sequence in the query match the sequence in the index? that is if the filter sequence in the query is filter b, filter c, and then order on a, then should it better to have compound index of (b, c, a)?

preguntado el 01 de febrero de 12 a las 04:02

2 Respuestas

Since MongoDB currently uses only one index per query, you will need a compound index.

The order of the index params does matter, although not necessarily in the way you mention in the question.

Since filtering happens first, if the index was (c,b,a), it wouldn't be very useful for filtering, especially if there are a lot of items in the collection. The fields used for sorting should be specified last in the index.

So the index should either be (a,b,c) or (b,a,c). Which one of those it should be depends on selectividad -- in other words, which field will eliminate items that don't match faster?

If there are 10,000 likely values for b, and only two likely values for a, then the index should be (b,a,c). Conversely, if there are many more possible values for a, then it should probably be (a,b,c). If the two fields are roughly the same in their ability to eliminate documents from the query, then it won't matter that much.

Respondido 02 Feb 12, 14:02

All of this and more is answered in the documentos. See the sections on compound indexes.

The order of the query params doesn't matter.

Respondido 01 Feb 12, 11:02

The order of fields in an index definitely matter, especially when some are used for filtering, and some for ordering. - Sean Reilly

The order of index fields matter as you explain in your answer, but the order of the query parameters does not. Given index {a:1, b:1} a query {b:"hi", a:23} will use that index. - Remon van Vliet

what if I have a geo field (assume it's c) and my query looks like - find(c nearby point1, a > 5).sort(b)? would a compound index of (c:2d, a:1, b:1) works and also is the order of c, a, b in the index the best order that fits to the query? - tom

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.