$where¶
-
$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.Warning
- Do not write to the database within the
$whereJavaScript function. $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 table scan.
Consider the following examples:
Additionally, if the query consists only of the
$whereoperator, 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
$whereoperator in your query, as in the following examples:Using normal non-
$wherequery statements provides the following performance advantages:- MongoDB will evaluate non-
$wherecomponents of query before$wherestatements. If the non-$wherestatements match no documents, MongoDB will not perform any query evaluation using$where. - The non-
$wherequery statements may use an index.
Note
Changed in version 2.4.
In MongoDB 2.4,
map-reduce operations, thegroupcommand, and$whereoperator expressions cannot access certain global functions or properties, such asdb, that are available in themongoshell.When upgrading to MongoDB 2.4, you will need to refactor your code if your
map-reduce operations,groupcommands, or$whereoperator expressions include any global shell functions or properties that are no longer available, such asdb.The following JavaScript functions and properties are available to
map-reduce operations, thegroupcommand, and$whereoperator expressions in MongoDB 2.4:Available Properties Available Functions argsMaxKeyMinKeyassert()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()- Do not write to the database within the