Database Manual / Reference / Query Language / Expressions

$divide (expression operator)(表达式运算符)

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.有关表达式的详细信息,请参阅表达式

Behavior行为

The default return type is a double. If at least one operand is a decimal, then the return type is a decimal.默认返回类型是double。如果至少有一个操作数是decimal,则返回类型是decimal

Examples示例

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 $divide expression to divide the hours field by a literal 8 to compute the number of work days:以下聚合使用$divide表达式将hours字段除以文字8来计算工作日数:

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

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

{ "_id" : 1, "city" : "New York", "workdays" : 10 }
{ "_id" : 2, "city" : "Singapore", "workdays" : 5 }