$where¶
-
$where
¶ Use the
$where
operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. The$where
provides greater flexibility, but requires that the database processes the JavaScript expression or function for each document in the collection. Reference the document in the JavaScript expression or function using eitherthis
orobj
.Warning
- Do not write to the database within the
$where
JavaScript function. $where
evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g.,$gt
,$in
).- In general, you should use
$where
only when you can’t express your query using another operator. If you must use$where
, try to include at least one other standard query operator to filter the result set. Using$where
alone requires a table scan.
Consider the following examples:
Additionally, if the query consists only of the
$where
operator, you can pass in just the JavaScript expression or JavaScript functions, as in the following examples:You can include both the standard MongoDB operators and the
$where
operator in your query, as in the following examples:Using normal non-
$where
query statements provides the following performance advantages:- Do not write to the database within the