$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描述
bodyString 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, ...) { ... }"

argsArray

Arguments passed to the function 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的替代方案

langString

The language used in the body. You must specify lang: "js".body中使用的语言。必须指定lang: "js"

Considerations注意事项

Schema Validation Restriction架构验证限制

You cannot use $function as part of schema validation query expression.不能将$function用作架构验证查询表达式的一部分。

Javascript Enablement支持Javascript

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:然而:

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

Note注意
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 $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"
} } } )
←  $floor (aggregation)$getField (aggregation) →