To ensure proper functionality, make sure to provide the $where
function as a string rather than an actual function. This allows Mongo to execute and process the function correctly (outside of Node.js environment). For further details on this topic, refer to this informative forum thread.
To implement this change, adjust your query as follows:
Tickers.find({"$where": "function() { return (this.price < this.value); }"})
Alternatively, you can simply use a string comparison like this:
Tickers.find("this.price < this.value");
Keep in mind that while using the $where
operator, performance may be affected as it requires JavaScript engine involvement to evaluate code for each document. It is advisable to combine such queries with indexes to enhance query speed.
When utilizing $where
, consider the following key factors:
Avoid using global variables.
$where
does not leverage indexes since it evaluates JavaScript code.
Hence, it is recommended to express queries using standard MongoDB operators (e.g., $gt
, $in
) whenever possible. Use $where
only when alternative operators are insufficient. If needed, combine $where
with other typical operators to achieve better results. Relying solely on $where
triggers table scans. Standard non-$where
queries offer enhanced performance advantages:
MongoDB assesses non-$where
components of query before evaluating $where
.
If non-$where
conditions result in zero matches, MongoDB mothballs $where
evaluation. Non-$where
queries might benefit from an index.
An alternate approach without relying extensively on the $where
operator involves creating an added computed field known as price_difference
, representing the price-value disparity, for simplified querying:
Tickers.find({ "price_difference": { "$gt": 0 }});
Nevertheless, low-selectivity fields like these may not optimize index performance for large collections due to broader indexing needs with this method.