Definition定义
$sqrtCalculates the square root of a positive number and returns the result as a double.计算正数的平方根,并将结果作为双精度数返回。$sqrthas the following syntax:具有以下语法:{ $sqrt: <number> }The argument can be any valid expression as long as it resolves to a non-negative number.参数可以是任何有效的表达式,只要它解析为非负数。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。
If the argument resolves to a value of 如果参数解析为null or refers to a field that is missing, $sqrt returns null. If the argument resolves to NaN, $sqrt returns NaN.null值或引用缺少的字段,则$sqrt返回null。如果参数解析为NaN,$sqrt将返回NaN。
$sqrt errors on negative numbers.对负数会发生错误。
{ $sqrt: 25 } | 5 |
{ $sqrt: 30 } | 5.477225575051661 |
{ $sqrt: null } | null |
Example示例
A collection 集合points contains the following documents:points包含以下文档:
db.points.insertMany( [
{ _id: 1, p1: { x: 5, y: 8 }, p2: { x: 0, y: 5} },
{ _id: 2, p1: { x: -2, y: 1 }, p2: { x: 1, y: 5} },
{ _id: 3, p1: { x: 4, y: 4 }, p2: { x: 4, y: 0} }
] )
The following example uses 以下示例使用$sqrt to calculate the distance between p1 and p2:$sqrt计算p1和p2之间的距离:
db.points.aggregate([
{
$project: {
distance: {
$sqrt: {
$add: [
{ $pow: [ { $subtract: [ "$p2.y", "$p1.y" ] }, 2 ] },
{ $pow: [ { $subtract: [ "$p2.x", "$p1.x" ] }, 2 ] }
]
}
}
}
}
])
The operation returns the following results:该操作返回以下结果:
{ _id: 1, distance: 5.830951894845301 }
{ _id: 2, distance: 5 }
{ _id: 3, distance: 4 }