$where¶
On this page
Definition¶
-
$where¶ Use the
$whereoperator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. The$whereprovides 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 eitherthisorobj.
Note
Starting in version 4.2.1, MongoDB deprecates the use of BSON
type JavaScript code with scope (BSON type 15) for the $where operator. Using
JavaScript code with scope with $where will print a warning
to the log. Instead, use BSON type String (BSON type 2) or BSON type JavaScript
(BSON type 13).
Important
Changed in version 3.6: The $expr operator allows the
use of aggregation expressions
within the query language. $expr is faster than
$where because it does not execute JavaScript and should
be preferred where possible.
Behavior¶
Restrictions¶
map-reduce operations and $where
operator expressions cannot access certain global functions or
properties, such as db, that are available in the
mongo shell.
The following JavaScript functions and properties are available to
map-reduce operations and $where
operator expressions:
| Available Properties | Available Functions | |
|---|---|---|
argsMaxKeyMinKey |
assert()BinData()DBPointer()DBRef()doassert()emit()gc()HexData()hex_md5()isNumber()isObject()ISODate()isString() |
Map()MD5()NumberInt()NumberLong()ObjectId()print()printjson()printjsononeline()sleep()Timestamp()tojson()tojsononeline()tojsonObject()UUID()version() |
elemMatch¶
Only apply the $where query operator to top-level
documents. The $where query operator will not work inside a
nested document, for instance, in an $elemMatch query.
Considerations¶
- Do not use global variables.
$whereevaluates 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
$whereonly 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$wherealone requires a collection scan.
Using normal non-$where query statements provides the
following performance advantages: