$where

On this page本页内容

Definition定义

$where

Use the $where operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. 使用$where运算符将包含JavaScript表达式的字符串或完整的JavaScript函数传递给查询系统。The $where provides greater flexibility, but requires that the database processes the JavaScript expression or function for each document in the collection. $where提供了更大的灵活性,但要求数据库为集合中的每个文档处理JavaScript表达式或函数。Reference the document in the JavaScript expression or function using either this or obj .使用thisobj在JavaScript表达式或函数中引用文档。

{ $where: <string|JavaScript Code> }
Note注意

Starting in MongoDB 4.4, $where no longer supports the deprecated BSON type JavaScript code with scope (BSON type 15). 从MongoDB 4.4开始,$where不再支持不推荐使用的范围为BSON类型的JavaScript代码(BSON类型15)。The $where operator only supports BSON type String (BSON type 2) or BSON type JavaScript (BSON type 13). $where运算符仅支持BSON类型String(BSON类型2)或BSON类型JavaScript(BSON类别13)。The use of BSON type JavaScript with scope for $where has been deprecated since MongoDB 4.2.1.自MongoDB 4.2.1以来,已不推荐使用范围为$where的BSON类型JavaScript。

Note注意
Aggregation Alternatives Preferred首选聚合替代方案

The $expr operator allows the use of aggregation expressions within the query language. $expr运算符允许在查询语言中使用聚合表达式And, starting in MongoDB 4.4, the $function and $accumulator allows users to define custom aggregation expressions in JavaScript if the provided pipeline operators cannot fulfill your application's needs.而且,从MongoDB 4.4开始,如果提供的管道运算符不能满足应用程序的需要,$function$accumulator允许用户在JavaScript中定义自定义聚合表达式。

Given the available aggregation operators:给定可用的聚合运算符:

  • The use of $expr with aggregation operators that do not use JavaScript (i.e. non-$function and non-$accumulator operators) is faster than $where because it does not execute JavaScript and should be preferred if possible.$expr与不使用JavaScript的聚合运算符(即非$function且非$accumulator运算符)一起使用要比$where快,因为它不执行JavaScript,如果可能的话应该优先使用。
  • However, if you must create custom expressions, $function is preferred over $where.但是,如果必须创建自定义表达式,则首选$function而不是$where

Behavior行为

Available JavaScript Properties and Functions可用的JavaScript属性和函数

map-reduce operations and $where operator expressions cannot access certain global functions or properties, such as db, that are available in mongosh.map-reduce操作$where运算符表达式无法访问mongosh中可用的某些全局函数或属性,例如db。

The following JavaScript functions and properties are available to map-reduce operations and $where operator expressions:以下JavaScript函数和属性可用于map-reduce操作和$where运算符表达式:

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-level documents. 仅将$where查询运算符应用于顶级文档。The $where query operator will not work inside a nested document, for instance, in an $elemMatch query.$where查询运算符不能在嵌套文档中工作,例如,在$elemMatch查询中。

Considerations注意事项

  • Do not use global variables.不要使用全局变量。
  • $where evaluates JavaScript and cannot take advantage of indexes. 评估JavaScript,无法利用索引。Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., $gt, $in).因此,当使用标准MongoDB运算符(例如$gt$in)表示查询时,查询性能会得到提高。
  • In general, you should use $where only when you cannot express your query using another operator. 通常,只有在无法使用其他运算符表达查询时,才应使用$whereIf you must use $where, try to include at least one other standard query operator to filter the result set. 如果必须使用$where,请尝试至少包含一个其他标准查询运算符来筛选结果集。Using $where alone requires a collection scan.单独使用$where需要进行集合扫描。

Using normal non-$where query statements provides the following performance advantages:使用普通的非$where查询语句可以提供以下性能优势:

  • MongoDB will evaluate non-$where components of query before $where statements. MongoDB将在$where语句之前评估查询的非$wheres组件。If the non-$where statements match no documents, MongoDB will not perform any query evaluation using $where.如果非$where语句与任何文档都不匹配,MongoDB将不会使用$where执行任何查询计算。
  • The non-$where query statements may use an index.$where查询语句可以使用索引

JavaScript EnablementJavaScript启用

To use $where (or $function, $accumulator, or mapReduce), you must have server-side scripting enabled (default).要使用$where(或$function$accumulatormapReduce),必须启用服务器端脚本(默认启用)。

However, if you do not use these operations, disable server-side scripting:但是,如果不使用这些操作,请禁用服务器端脚本:

See also ➤ Run MongoDB with Secure Configuration Options.另请参阅➤ 使用安全配置选项运行MongoDB

Example示例

Consider the following documents in the players collection:考虑players集合中的以下文档:

db.players.insertMany([
   { _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 an MD5 hash and returns any matching document.下面的示例使用$wherehex_md5()JavaScript函数将名称字段的值与md5哈希进行比较,并返回任何匹配的文档。

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"
}

As an alternative, the previous example can be rewritten using $expr and $function. 或者,可以使用$expr$function重写前面的示例。Starting in MongoDB 4.4, you can define custom aggregation expression in JavaScript with the aggregation operator $function. 从MongoDB 4.4开始,您可以使用聚合运算符$function在JavaScript中定义自定义聚合表达式。To access $function and other aggregation operators in db.collection.find(), use with $expr:要访问db.collection.find()中的$function和其他聚合运算符,请与$expr配合使用:

db.players.find( {$expr: { $function: {
      body: function(name) { return hex_md5(name) == "9b53e667f30cd329dca1ec9e6a83e994"; },
      args: [ "$name" ],
      lang: "js"
} } } )

If you must create custom expressions, $function is preferred over $where.如果必须创建自定义表达式,则首选$function而不是$where

←  $textGeospatial Query Operators →