Pergunta

From MongoDB Documentation

If you have a compound index on multiple fields, you can use it to query on the beginning subset of fields. So if you have an index on a,b,c you can use it query on [a] [a,b] [a,b,c]

So lets say i have document with this fields

  1. UserID
  2. Name
  3. Country
  4. ExtraField

My Index order is [UserID,Name,Country]

So if i have query like

  var q = (from c in collection.AsQueryable()
                 where c.UserID == UserID
                 where Name = "test"
                 where Country = 1
                 where ExtraField = "check"

                 select c);

Does this query use index for first 3 parameters and then search for ExtraField without index?

If yes, then is it same on this query too

 var q = (from c in collection.AsQueryable()
                 where c.UserID == UserID                   
                 where ExtraField = "check"

                 select c);
Foi útil?

Solução

The answer to both questions is yes.

For your first query, the performance will depend on the selectivity of the result set. So if the 3 fields in the index matched a very large number of documents, performance would be slow as all those documents would need to be scanned to match on ExtraField. If only a few documents were matched, performance would be fast.

Now, if your query didn't include the first field in the index at all, the index would not be used. The following query, for example, would not be able to use the index:

var q = (from c in collection.AsQueryable()
              where Name = "test"
              where Country = 1
              select c);

Have a look here for some interesting facts about finding other combinations of fields in the index.

I would recommend using the explain command when in doubt about questions like this.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top