When creating a simple MongoDB query, I have a question about the ordering of conditions in the query - for example (Mongoose.js syntax):
co
I'm a little confused by your question, simply because the index you provide ({ first_name: 1, archived: 1 }
) is a compound index. All of the following queries will make use of that compound index:
conditions = { archived: false, first_name: "Billy" };
conditions = { first_name: "Billy", archived: false };
conditions = { first_name: "Billy" };
Now, let's assume we have two separate indexes, { first_name: 1 }
and { archived: 1 }
. In this case, MongoDB will do query optimization to determine which index is the most efficient to use. You can read more about the query optimization performed by MongoDB here.
The MongoDB query optimizer will thus likely use the same index for both of the multicondition queries you provided:
conditions = { archived: false, first_name: "Billy" };
conditions = { first_name: "Billy", archived: false };
Alternatively, you can use hint to force MongoDB to use an index of your choosing. In general, this is probably not a good idea. You can also manually check which index is the most efficient for a specific query as detailed here.
You can see which index a query is using by using the .explain() functionality in the Mongo shell. (If no index is used, you'll see "cursor" : "BasicCursor"
in the resulting document. On the other hand, if the compound index is being used, you'll see something like "cursor" : "BtreeCursor first_name_1_archived_1"
. If one of the single-field indexes was used, you might see "cursor" : "BtreeCursor archived_1"
.
Additionally, the search strategy for MongoDB works like this:
The query optimizer runs all possible query plans in parallel and picks the "best" one, however all of the query plans follow the strategy above. (The BasicCursor is a degenerate case: it traverses all of the documents & applies the predicate to each one.)
tl;dr? The Matcher is smart enough to match equality predicates when they're presented in any order.
Does that make sense?