Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo compound indexes, using less-than-all in a query

Tags:

mongodb

I understand that with MongoDB, for a query to make use of a compound index it must use ALL of the keys in the index, or at least some of the keys starting from the left. For example

db.products.find({ "a":"foo", "b":"bar" })

Will happily make use of an index made up of {a, b, c}.

However, if I want to query:

db.products.find( {"a":"foo", "c":"thing" })

I believe this can't use the index. Could this be solved by adding a trivial condition on "b", e.g.

db.products.find( {"a":"foo", "b":{ $ne : "" }, "c":"thing" })

Even when I don't actually care about the value of b. The reason for this is that we currently have 45m objects, and it's going to continue growing so we're looking to consolidate our indexes to save on resources.

Many thanks.

like image 438
Chris Avatar asked Nov 02 '11 08:11

Chris


People also ask

Can a query use multiple indexes MongoDB?

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.

Can MongoDB use part of a compound index?

MongoDB can use the intersection of indexes to fulfill queries. For queries that specify compound query conditions, if one index can fulfill a part of a query condition, and another index can fulfill another part of the query condition, then MongoDB can use the intersection of the two indexes to fulfill the query.

How do I create a unique compound index in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

How does MongoDB decide which index to use?

MongoDB uses multikey indexes to index the content stored in arrays. If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays.


1 Answers

In general, a query on a multi-column index that does not sufficiently limit matches for one of the columns will restrict the usefulness of the multi-column index. In your example, using query criteria of {"a":"foo", "b":{$ne:""}, "c":"thing"} will limit the usefulness of an {a,b,c} index to matching only on a. If your query criteria will be executed often, create an {a,c,b} index (or {a,c} if b will not be used in query criteria).

Use the explain function on your queries to see if an index is being used to its full potential. If explain tells you indexOnly is true, then your query is only using the index to find matching documents; otherwise, MongoDB needs to look at each document to find matches.

For further information, see:

  • Optimization
  • Indexes
  • Query Optimizer
like image 155
Dan Cruz Avatar answered Oct 11 '22 04:10

Dan Cruz