On this page本页内容
$abs
Returns the absolute value of a number.返回数字的绝对值。
$abs has 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.有关表达式的详细信息,请参阅表达式。
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 |
A collection ratings contains the following documents:ratings集合包含以下文件:
{ _id: 1, start: 5, end: 8 }
{ _id: 2, start: 4, end: 4 }
{ _id: 3, start: 9, end: 7 }
{ _id: 4, start: 6, end: 7 }
The following example calculates the magnitude of difference between the 以下示例计算start and end ratings:start和end评分值之间的差值:
db.ratings.aggregate([
{
$project: { delta: { $abs: { $subtract: [ "$start", "$end" ] } } }
}
])
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "delta" : 3 }
{ "_id" : 2, "delta" : 0 }
{ "_id" : 3, "delta" : 2 }
{ "_id" : 4, "delta" : 1 }