$mod (aggregation)

On this page本页内容

Definition定义

$mod

Divides one number by another and returns the remainder.将一个数除以另一个数并返回余数

The $mod expression has the following syntax:$mod表达式语法如下所示:

{ $mod: [ <expression1>, <expression2> ] }

The first argument is the dividend, and the second argument is the divisor; i.e. first argument is divided by the second argument.第一个参数是股息,第二个参数是除数;第一个论点除以第二个论点。

The arguments can be any valid expression as long as they resolve to numbers. 参数可以是任何有效的表达式,只要它们解析为数字。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Example示例

Consider a planning collection with the following documents:考虑一个planning集合带有以下文档:

{ "_id" : 1, "project" : "A", "hours" : 80, "tasks" : 7 }
{ "_id" : 2, "project" : "B", "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.planning.aggregate(
   [
     { $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } }
   ]
)

The operation returns the following results:操作返回以下结果:

{ "_id" : 1, "remainder" : 3 }
{ "_id" : 2, "remainder" : 0 }