$where
Definition
$where
- Use the
$where
operator to pass either a stringcontaining a JavaScript expression or a full JavaScript function tothe query system. The$where
provides greaterflexibility, but requires that the database processes theJavaScript expression or function for each document in thecollection. Reference the document in the JavaScript expression orfunction using eitherthis
orobj
.
Important
Changed in version 3.6: The $expr
operator allows theuse of aggregation expressionswithin the query language. $expr
is faster than$where
because it does not execute JavaScript and shouldbe preferred where possible.
Behavior
Restrictions
map-reduce operations
and $where
operator expressions cannot access certain global functions orproperties, such as db
, that are available in themongo
shell.
The following JavaScript functions and properties are available tomap-reduce operations
and $where
operator expressions:
Available Properties | Available Functions | |
---|---|---|
args MaxKey MinKey | 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-leveldocuments. The $where
query operator will not work inside anested document, for instance, in an $elemMatch
query.
Considerations
- Do not use global variables.
$where
evaluates JavaScript and cannot takeadvantage of indexes. Therefore, query performance improveswhen you express your query using the standard MongoDBoperators (e.g.,$gt
,$in
).- In general, you should use
$where
only when youcan’t express your query using another operator. If you mustuse$where
, try to include at least one otherstandard query operator to filter the result set. Using$where
alone requires a collection scan.
Using normal non-$where
query statements provides thefollowing performance advantages:
- MongoDB will evaluate non-
$where
components of querybefore$where
statements. If thenon-$where
statements match no documents, MongoDBwill not perform any query evaluation using$where
. - The non-
$where
query statements may use anindex.
Example
Consider the following documents in the players
collection:
- {
- _id: 12378,
- name: "Steve",
- username: "steveisawesome",
- first_login: "2017-01-01"
- }
- {
- _id: 2,
- name: "Anya",
- username: "anya",
- first_login: "2001-02-02"
- }
The following example uses $where
and the hex_md5()
JavaScript function to compare the value of the name
field to anMD5 hash and returns any matching document.
- db.players.find( { $where: function() {
- return (hex_md5(this.name) == "9b53e667f30cd329dca1ec9e6a83e994")
- } } );
The operation returns the following result:
- {
- "_id" : 2,
- "name" : "Anya",
- "username" : "anya",
- "first_login" : "2001-02-02"
- }