$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

Important

Executing 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"
  }
}
Field字段Type类型Description描述
body String or 或者Code

The function definition. 函数定义。You can specify the function definition as either BSON type Code or String. 可以将函数定义指定为BSON类型代码或字符串。See also lang.另见lang

function(arg1, arg2, ...) { ... }

or或者

"function(arg1, arg2, ...) { ... }"

args Array

Arguments passed to the function body. 传递给函数body的参数。If the body function does not take an argument, you can specify an empty array [ ].如果body函数不接受参数,则可以指定空数组[]

The array elements can be any BSON type, including Code. 数组元素可以是任何BSON类型,包括代码。See Example 2: Alternative to $where.请参阅示例2:除了$where之外的其他选择

lang String

The language used in the body. body中使用的语言。You must specify lang: "js".必须指定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$wheremapReduce),请禁用服务器端脚本:

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

Alternative to $where除了$where之外的其他选择

The query operator $where can also be used to specify JavaScript expression. 查询运算符$where也可用于指定JavaScript表达式。However:

  • Starting in MongoDB 3.6, the $expr operator allows the use of aggregation expressions within the query language.从MongoDB 3.6开始,$expr运算符允许在查询语言中使用聚合表达式
  • 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

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的值由检查名称的MD5哈希是否等于指定哈希的自定义$function表达式确定。
  • message whose value is determined by the custom $function expression that format a string message using a template.其值由自定义$function表达式确定的message,该表达式使用模板格式化字符串消息。
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的选项

Aggregation Alternatives Preferred over $where聚合替代方案优先于$where

Starting in MongoDB 3.6, the $expr operator allows the use of aggregation expressions within the query language. 从MongoDB 3.6开始,$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

As an alternative to a query that uses the $where operator, you can use $expr and $function. 作为使用$where运算符的查询的替代方法,可以使用$expr$functionFor example, consider the following $where example.例如,考虑下面的$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"
} } } )