$function (aggregation)
On this page本页内容
Definition定义
$function
New in version 4.4.4.4版新增。Defines a custom aggregation function or expression in JavaScript.在JavaScript中定义自定义聚合函数或表达式。You can use the您可以使用$function
operator to define custom functions to implement behavior not supported by the MongoDB Query Language.$function
运算符来定义自定义函数,以实现MongoDB查询语言不支持的行为。See also另请参阅$accumulator
.$accumulator
。ImportantExecuting JavaScript inside an aggregation expression may decrease performance.在聚合表达式中执行JavaScript可能会降低性能。Only use the如果提供的管道运算符不能满足应用程序的需要,则仅使用$function
operator if the provided pipeline operators cannot fulfill your application's needs.$function
运算符。
Syntax语法
The $function
operator has the following syntax:$function
运算符具有以下语法:
{
$function: {
body: <code>,
args: <array expression>,
lang: "js"
}
}
body | String or Code | lang 。function(arg1, arg2, ...) { ... } or "function(arg1, arg2, ...) { ... }" |
args | Array | [ ] .body 函数不带参数,则可以指定一个空数组[] 。$where . $where 的替代方案。 |
lang | String | lang: "js" . body 中使用的语言。您必须指定lang: "js" 。 |
Considerations注意事项
Schema Validation Restriction架构验证限制
You cannot use 不能将$function
as part of schema validation query expression.$function
用作架构验证查询表达式的一部分。
Javascript EnablementJavascript启用
To use 若要使用$function
, you must have server-side scripting enabled (default).$function
,必须启用服务器端脚本(默认设置)。
If you do not use 如果不使用$function
(or $accumulator
, $where
, or mapReduce
), disable server-side scripting:$function
(或$accumulator
、$where
或mapReduce
),请禁用服务器端脚本:
For a对于mongod
instance, seesecurity.javascriptEnabled
configuration option or--noscripting
command-line option.mongod
实例,请参阅security.javascriptEnabled
配置选项或--noscripting
命令行选项。For a对于mongos
instance, seesecurity.javascriptEnabled
configuration option or the--noscripting
command-line option starting in MongoDB 4.4.mongos
实例,请参阅从MongoDB 4.4开始的security.javascriptEnabled
配置选项或--noscripting
命令行选项。
In earlier versions, MongoDB does not allow JavaScript execution on在早期版本中,MongoDB不允许在mongos
instances.mongos
实例上执行JavaScript。
See also ➤ Run MongoDB with Secure Configuration Options.另请参阅➤ 使用安全配置选项运行MongoDB。
Alternative to $where
替代$where
$where
The query operator 查询运算符$where
can also be used to specify JavaScript expression. However:$where
也可以用于指定JavaScript表达式。但是:
The$expr
operator allows the use of aggregation expressions within the query language.$expr
运算符允许在查询语言中使用聚合表达式。Starting in MongoDB 4.4, the从MongoDB 4.4开始,$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$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
。
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. $accumulator
、$function
和$where
表达式的内部JavaScript引擎,并从MozJS-60升级到MozJS-91。Several deprecated, non-standard array and string functions that existed in MozJS-60 are removed in MozJS-91.MozJS-60中存在的一些不推荐使用的非标准数组和字符串函数在MozJS-91中被删除。
For the complete list of removed array and string functions, see the 6.0 compatibility notes.有关已删除的数组和字符串函数的完整列表,请参阅6.0兼容性说明。
Examples实例
Example 1: Usage Example示例1:用法示例
Create a sample collection named 使用以下文档创建一个名为players
with the following documents:players
的示例集合:
db.players.insertMany([
{ _id: 1, name: "Miss Cheevous", scores: [ 10, 5, 10 ] },
{ _id: 2, name: "Miss Ann Thrope", scores: [ 10, 10, 10 ] },
{ _id: 3, name: "Mrs. Eppie Delta ", scores: [ 9, 8, 8 ] }
])
The following aggregation operation uses 以下聚合操作使用$addFields
to add new fields to each document:$addFields
向每个文档添加新字段:
isFound
whose value is determined by the custom$function
expression that checks whether the MD5 hash of the name is equal to a specified hash.isFound
,其值由自定义$function
表达式确定,该表达式检查名称的MD5哈希是否等于指定的哈希。message
whose value is determined by the custom$function
expression that format a string message using a template.message
,其值由使用模板格式化字符串消息的自定义$function
表达式确定。
db.players.aggregate( [
{ $addFields:
{
isFound:
{ $function:
{
body: function(name) {
return hex_md5(name) == "15b0a220baa16331e8d80e15367677ad"
},
args: [ "$name" ],
lang: "js"
}
},
message:
{ $function:
{
body: function(name, scores) {
let total = Array.sum(scores);
return `Hello ${name}. Your total score is ${total}.`
},
args: [ "$name", "$scores"],
lang: "js"
}
}
}
}
] )
The operation returns the following documents:该操作返回以下文档:
{ "_id" : 1, "name" : "Miss Cheevous", "scores" : [ 10, 5, 10 ], "isFound" : false, "message" : "Hello Miss Cheevous. Your total score is 25." }
{ "_id" : 2, "name" : "Miss Ann Thrope", "scores" : [ 10, 10, 10 ], "isFound" : true, "message" : "Hello Miss Ann Thrope. Your total score is 30." }
{ "_id" : 3, "name" : "Mrs. Eppie Delta ", "scores" : [ 9, 8, 8 ], "isFound" : false, "message" : "Hello Mrs. Eppie Delta . Your total score is 25." }
Example 2: Alternative to $where
示例2:$where
的替代方案
$where
Aggregation Alternatives Preferred over $where聚合备选方案优先于$where
The $expr
operator allows the use of aggregation expressions within the query language. $expr
运算符允许在查询语言中使用聚合表达式。And, starting in MongoDB 4.4, the 而且,从MongoDB 4.4开始,如果提供的管道运算符无法满足应用程序的需求,那么$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$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
。
As an alternative to a query that uses the 作为使用$where
operator, you can use $expr
and $function
. For example, consider the following $where
example.$where
运算符的查询的替代方案,您可以使用$expr
和$function
。例如,考虑下面的$where
示例。
db.players.find( { $where: function() {
return (hex_md5(this.name) == "15b0a220baa16331e8d80e15367677ad")
} } );
The db.collection.find()
operation returns the following document:db.collection.find()
操作返回以下文档:
{ "_id" : 2, "name" : "Miss Ann Thrope", "scores" : [ 10, 10, 10 ] }
The example can be expressed using 该示例可以使用$expr
and $function
:$expr
和$function
来表示:
db.players.find( {$expr: { $function: {
body: function(name) { return hex_md5(name) == "15b0a220baa16331e8d80e15367677ad"; },
args: [ "$name" ],
lang: "js"
} } } )