$divide (aggregation)

On this page本页内容

Definition定义

$divide

Divides one number by another and returns the result. 将一个数除以另一个数并返回结果。Pass the arguments to $divide in an array.将参数传递给数组中的$divide

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

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

The first argument is the dividend, and the second argument is the divisor; i.e. the 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.有关表达式的详细信息,请参阅表达式

Examples示例

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

{ "_id" : 1, "name" : "A", "hours" : 80, "resources" : 7 },
{ "_id" : 2, "name" : "B", "hours" : 40, "resources" : 4 }

The following aggregation uses the $divide expression to divide the hours field by a literal 8 to compute the number of work days:下面的聚合使用$divide表达式将hour字段除以8来计算工作日数:

db.planning.aggregate(
   [
     { $project: { name: 1, workdays: { $divide: [ "$hours", 8 ] } } }
   ]
)

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

{ "_id" : 1, "name" : "A", "workdays" : 10 }
{ "_id" : 2, "name" : "B", "workdays" : 5 }