$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 either this or obj .

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 $whereoperator 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 $whereoperator expressions:

Available PropertiesAvailable 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()

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:

  1. {
  2. _id: 12378,
  3. name: "Steve",
  4. username: "steveisawesome",
  5. first_login: "2017-01-01"
  6. }
  7. {
  8. _id: 2,
  9. name: "Anya",
  10. username: "anya",
  11. first_login: "2001-02-02"
  12. }

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.

  1. db.players.find( { $where: function() {
  2. return (hex_md5(this.name) == "9b53e667f30cd329dca1ec9e6a83e994")
  3. } } );

The operation returns the following result:

  1. {
  2. "_id" : 2,
  3. "name" : "Anya",
  4. "username" : "anya",
  5. "first_login" : "2001-02-02"
  6. }