MongoDB 加减乘除 $add、$subtract、$mul
2019-11-14 本文已影响0人
沧海2122537190
1、$add
加法运算,基础语法:{ $add : [ < expression1 > , < expression2 > , ... ] }
2、$subtract
减法运算,基础语法:{ $subtract: [ <expression1>, <expression2> ] }
expression1减去expression2
3、$multiply
乘法运算,基础语法:{ $multiply : [ < expression1 > , < expression2 > , ... ] }
4、$divide
除法运算,基础语法:{ $divide: [ <expression1>, <expression2> ] }
expression1为被除数,expression2为除数
上述4个基础语法中 <expression>是需要运算的字段或数字,add 和multiply 的<expression>可以多于2个。见例三
注:
1.以上4个都只支持对数字类型的的字段进行运算,字符串类型不可以。见例一
2.Int类型和Double之间可以运算。见例二
3.当 <expression>中有一个不存在或为null时,运算结果皆为空。见例二
4.时间(DateTime)可以计算,加减的最终结果是毫秒。
5.若是String类型的时间,需用$dateFromString
转换为时间类型在计算。
示例:

其中蓝色底是的数据类型是Double,绿色底的数据类型是Int32,红色底的数据类型是String
例一:对fyear和lyear,进行加减乘除运算
db.getCollection("mathematical_test").aggregate([{
$project: {
title: 1,
"add": {$add: ["$fyear", "$lyear"]},
"subtract":{$subtract:["$fyear", "$lyear"]},
"multiply":{$multiply:["$fyear", "$lyear"]},
"divide":{$divide:["$fyear", "$lyear"]}
}
}])

报错分别为
$add only supports numeric or date types, not string
cant $subtract astring from a string
$multiply only supports numeric types, not string
$divide only supports numeric types, not string and string
例二:对first_year和last_year,进行加减乘除运算
db.getCollection("mathematical_test").aggregate([{
$project: {
title: 1,first_year:1,last_year:1,
"add": {$add: ["$first_year", "$last_year"]},
"subtract":{$subtract:["$first_year", "$last_year"]},
"multiply":{$multiply:["$first_year", "$last_year"]},
"divide":{$divide:["$first_year", "$last_year"]}
}
}])

例三:多值计算
db.getCollection("mathematical_test").aggregate([{
$project: {
title: 1,first_year:1,last_year:1,
"add": {$add: ["$first_year", "$last_year",1,5]},
"add1": {$add: [1,2,3,4,5]},
"multiply":{$multiply:["$first_year", "$last_year",2,10]},
"multiply1":{$multiply:[1,2,3,4,5]},
}
}])

例四:多次计算
a1=first_year-20+last_year
a2=first_year20+last_year
a3=(first_year+2000)(last_year-2010)
db.getCollection("mathematical_test").aggregate([{
$project: {
title: 1,
first_year: 1,
last_year: 1,
"a1": {$add: [{$subtract: ["$first_year", 20]},"$last_year"]},
"a2": {$add: [{$multiply: ["$first_year", 20]},"$last_year"]},
"a3": {$multiply: [{$add: ["$first_year", 2000]},{$subtract: ["$last_year", 2010]}]},
}}])
