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.
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.
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.
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With