1、$add
加法運(yùn)算,基礎(chǔ)語法:{ $add : [ < expression1 > , < expression2 > , ... ] }
2、$subtract
減法運(yùn)算,基礎(chǔ)語法:{ $subtract: [ <expression1>, <expression2> ] } expression1減去expression2
3、$multiply
乘法運(yùn)算,基礎(chǔ)語法:{ $multiply : [ < expression1 > , < expression2 > , ... ] }
4、$divide
除法運(yùn)算,基礎(chǔ)語法:{ $divide: [ <expression1>, <expression2> ] }expression1為被除數(shù),expression2為除數(shù)
上述4個基礎(chǔ)語法中 <expression>是需要運(yùn)算的字段或數(shù)字,add 和multiply 的<expression>可以多于2個。見例三
注:
1.以上4個都只支持對數(shù)字類型的的字段進(jìn)行運(yùn)算,字符串類型不可以。見例一
2.Int類型和Double之間可以運(yùn)算。見例二
3.當(dāng) <expression>中有一個不存在或為null時,運(yùn)算結(jié)果皆為空。見例二
4.時間(DateTime)可以計算,加減的最終結(jié)果是毫秒。
5.若是String類型的時間,需用$dateFromString轉(zhuǎn)換為時間類型在計算。
示例:

運(yùn)算樣例數(shù)據(jù)
其中藍(lán)色底是的數(shù)據(jù)類型是Double,綠色底的數(shù)據(jù)類型是Int32,紅色底的數(shù)據(jù)類型是String
例一:對fyear和lyear,進(jìn)行加減乘除運(yùn)算
db.getCollection("mathematical_test").aggregate([{
$project: {
title: 1,
"add": {$add: ["$fyear", "$lyear"]},
"subtract":{$subtract:["$fyear", "$lyear"]},
"multiply":{$multiply:["$fyear", "$lyear"]},
"divide":{$divide:["$fyear", "$lyear"]}
}
}])

結(jié)果報錯
報錯分別為
$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,進(jìn)行加減乘除運(yùn)算
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"]}
}
}])

計算結(jié)果
例三:多值計算
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]},
}
}])

計算結(jié)果
例四:多次計算
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]}]},
}}])

計算結(jié)果