Definition定义
$where-
Important
Server-side JavaScript Deprecated服务器端JavaScript已弃用Starting in MongoDB 8.0, server-side JavaScript functions (从MongoDB 8.0开始,服务器端JavaScript函数($accumulator,$function,$where) are deprecated. MongoDB logs a warning when you run these functions.$accumulator、$function、$where)被弃用。当您运行这些函数时,MongoDB会记录一个警告。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.$where运算符将包含JavaScript表达式的字符串或完整的JavaScript函数传递给查询系统。$where提供了更大的灵活性,但要求数据库处理集合中每个文档的JavaScript表达式或函数。Reference the document in the JavaScript expression or function using either使用thisorobj.this或obj在JavaScript表达式或函数中引用文档。
Compatibility兼容性
You can use 您可以将$where for deployments hosted in the following environments:$where用于在以下环境中托管的部署:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Syntax语法
The $where operator has the following form:$where运算符具有以下形式:
{ $where: <string|JavaScript Code> }
Note
$其中不再支持已弃用的带作用域的BSON类型JavaScript代码(BSON类型15)。$where no longer supports the deprecated BSON type JavaScript code with scope (BSON Type 15). The $where operator only supports BSON type String (BSON Type 2) or BSON type JavaScript (BSON Type 13). The use of BSON type JavaScript with scope for $where has been deprecated since MongoDB 4.2.1.$where运算符仅支持BSON类型字符串(BSON类型2)或BSON类型JavaScript(BSON type 13)。自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运算符允许在查询语言中使用聚合表达式。The 如果提供的管道运算符无法满足应用程序的需求,$function and $accumulator allows users to define custom aggregation expressions in JavaScript if the provided pipeline operators cannot fulfill your application's needs.$function和$accumulator允许用户在JavaScript中定义自定义聚合表达式。
Given the available aggregation operators:给定可用的聚合运算符:
The use of将$exprwith aggregation operators that do not use JavaScript (i.e. non-$functionand non-$accumulatoroperators) is faster than$wherebecause it does not execute JavaScript and should be preferred if possible.$expr与不使用JavaScript的聚合运算符(即非$function和非$accumulator运算符)一起使用比$where更快,因为它不执行JavaScript,如果可能的话应该是首选。However, if you must create custom expressions,但是,如果必须创建自定义表达式,则$functionis preferred over$where.$function比$where更可取。
Behavior行为
Available JavaScript Properties and Functions可用的JavaScript属性和函数
map-reduce操作和map-reduce operations and $where operator expressions cannot access certain global functions or properties, such as db, that are available in mongosh.$where运算符表达式无法访问mongosh中可用的某些全局函数或属性,如db。
The following JavaScript functions and properties are available to 以下JavaScript函数和属性可用于map-reduce操作和map-reduce operations and $where operator expressions:$where运算符表达式:
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.$where查询运算符应用于顶级文档。$where查询运算符在嵌套文档中不起作用,例如在$elemMatch查询中。
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.,评估JavaScript,无法利用索引。因此,当您使用标准MongoDB运算符(例如$gt,$in).$gt、$in)表示查询时,查询性能会得到提高。In general, you should use一般来说,只有在无法使用其他运算符表达查询时,才应使用$whereonly when you cannot 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.$where。如果必须使用$where,请尝试至少包含一个其他标准查询运算符来筛选结果集。仅使用$where需要进行集合扫描。
Using normal non-使用普通的非$where query statements provides the following performance advantages:$where查询语句可以提供以下性能优势:
MongoDB will evaluate non-MongoDB将在$wherecomponents of query before$wherestatements.$where语句之前评估查询的非$where组件。If the non-如果非$wherestatements match no documents, MongoDB will not perform any query evaluation using$where.$where语句不匹配任何文档,MongoDB将不会使用$where执行任何查询计算。The non-非$wherequery 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、$accumulator或mapReduce),您必须启用服务器端脚本(默认)。
However, if you do not use these operations, disable server-side scripting:但是,如果不使用这些操作,请禁用服务器端脚本:
For a对于mongodinstance, seesecurity.javascriptEnabledconfiguration option or--noscriptingcommand-line option.mongod实例,请参阅security.javascriptEnabled配置选项或--noscripting命令行选项。For a对于mongosinstance, seesecurity.javascriptEnabledconfiguration option or the--noscriptingcommand-line option.mongos实例,请参阅security.javascriptEnabled配置选项或--noscripting命令行选项。
See also ➤ Run MongoDB with Secure Configuration Options.另请参阅使用安全配置选项运行MongoDB。
Unsupported Array and String Functions不支持的数组和字符串函数
MongoDB 6.0 upgrades the internal JavaScript engine used for server-side JavaScript, MongoDB 6.0将用于服务器端JavaScript、$accumulator, $function, and $where expressions and from MozJS-60 to MozJS-91. Several deprecated, non-standard array and string functions that existed in MozJS-60 are removed in MozJS-91.$accumulator、$function和$where表达式的内部JavaScript引擎从MozJS-60升级到MozJS-91。MozJS-60中存在的几个已弃用的非标准数组和字符串函数在MozJS-91中被删除。
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.$where和hex_md5()JavaScript函数将name字段的值与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重写前面的示例。You can define custom aggregation expression in JavaScript with the aggregation operator 您可以使用聚合运算符$function. $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。