$abs (aggregation)
On this page本页内容
Definition定义
$abs-
Returns the absolute value of a number.返回数字的绝对值。$abshas the following syntax:具有以下语法:{ $abs: <number> }The<number>expression can be any valid expression as long as it resolves to a number.<number>表达式可以是任何有效的表达式,只要它解析为数字即可。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
Behavior行为
If the argument resolves to a value of 如果参数解析为null or refers to a field that is missing, $abs returns null. null值或引用了缺失的字段,$abs将返回null。If the argument resolves to 如果参数解析为NaN, $abs returns NaN.NaN,$abs将返回NaN。
{ $abs: -1 } | 1 |
{ $abs: 1 } | 1 |
{ $abs: null } | null |
Example实例
A collection 集合temperatureChange contains the following documents:temperatureChange包含以下文档:
db.temperatureChange.insertMany( [
{ _id: 1, startTemp: 50, endTemp: 80 },
{ _id: 2, startTemp: 40, endTemp: 40 },
{ _id: 3, startTemp: 90, endTemp: 70 },
{ _id: 4, startTemp: 60, endTemp: 70 }
] )
The following example calculates the magnitude of difference between the 以下示例计算startTemp and endTemp ratings:startTemp和endTemp额定值之间的差值大小:
db.temperatureChange.aggregate([
{
$project: { delta: { $abs: { $subtract: [ "$startTemp", "$endTemp" ] } } }
}
])
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "delta" : 30 }
{ "_id" : 2, "delta" : 0 }
{ "_id" : 3, "delta" : 20 }
{ "_id" : 4, "delta" : 10 }