Definition定义
$modDivides one number by another and returns the remainder.将一个数字除以另一个数字,然后返回余数。
Syntax语法
The $mod expression has the following syntax:$mod表达式具有以下语法:
{ $mod: [ <expression1>, <expression2> ] }
The first argument is the dividend, and the second argument is the divisor. That is, the first argument is divided by the second argument.第一个参数是被除数,第二个参数是除数。也就是说,第一个参数被第二个参数所分割。
Behavior行为
The arguments can be any valid expression as long as they resolve to numbers. 参数可以是任何有效的表达式,只要它们解析为数字。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
Starting in version 7.2, the output data type of the 从7.2版本开始,$mod operator is the larger of the two input data types.$mod运算符的输出数据类型是两种输入数据类型中较大的一种。
Note
Prior to version 7.2, the value and field type of inputs determine the 在7.2版本之前,如果满足以下条件,则输入的值和字段类型决定了$mod output type if:$mod输出类型:
The divisor is type除数类型为doublebut has an integer value.double,但具有整数值。The dividend is type被除数类型为intorlong.int或long。
In this case, MongoDB converts the divisor to the dividend data type before it performs the 在这种情况下,MongoDB在执行$mod operation. The output data type is the dividend data type.$mod操作之前将除数转换为被除数数据类型。输出数据类型为被除数数据类型。
Negative Dividend负被除数
When the dividend is negative, the remainder is also negative. For more details on this behavior, see the official JavaScript documentation.当被除数为负时,剩余部分也为负。有关此行为的更多详细信息,请参阅官方JavaScript文档。
For an example, see Negative Dividend.例如,请参阅负被除数。
Example示例
Consider a 考虑一个包含以下文件的conferencePlanning collection with the following documents:conferencePlanning集合:
db.conferencePlanning.insertMany( [
{ "_id" : 1, "city" : "New York", "hours" : 80, "tasks" : 7 },
{ "_id" : 2, "city" : "Singapore", "hours" : 40, "tasks" : 4 }
] )
The following aggregation uses the 以下聚合使用$mod expression to return the remainder of the hours field divided by the tasks field:$mod表达式返回hours字段除以tasks字段的剩余部分:
db.conferencePlanning.aggregate( [
{ $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } }
] )
The operation returns the following results:该操作返回以下结果:
[
{ '_id' : 1, 'remainder' : 3 },
{ '_id' : 2, 'remainder' : 0 }
]
Negative Dividend负红利
Consider a 考虑一个包含以下文档的modExample collection that contains the following document:modExample集合:
db.modExample.insertOne( [
{ "_id" : 1, "dividend": -13, "divisor": 9 }
] )
This aggregation uses the 此聚合使用$mod expression to return the remainder of dividend divided by the divisor field:$mod表达式返回dividend字段除以divisor的余数:
db.modExample.aggregate( [
{ $project: { remainder: { $mod: [ "$dividend", "$divisor" ] } } }
] )
The operation returns the following results:该操作返回以下结果:
[ { '_id' : 1, 'remainder' : -4 } ]