On this page
$sqrt (aggregation)
在本页面
Definition
$sqrt
- 3.2 版中的新功能。
计算正数的平方根,然后将结果作为双精度值返回。
$sqrt具有以下语法:
{ $sqrt: <number> }
该参数可以是任何有效的expression,只要它可以解析为非负数即可。有关表达式的更多信息,请参见Expressions。
Behavior
如果参数解析为null
的值或引用了缺少的字段,则$sqrt
返回null
。如果参数解析为NaN
,则$sqrt
返回NaN
。
$sqrt负数错误。
Example | Results |
---|---|
{ $sqrt: 25 } |
5 |
{ $sqrt: 30 } |
5.477225575051661 |
{ $sqrt: null } |
null |
Example
集合points
包含以下文档:
{ _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} }
以下示例使用$sqrt计算p1
和p2
之间的距离:
db.points.aggregate([
{
$project: {
distance: {
$sqrt: {
$add: [
{ $pow: [ { $subtract: [ "$p2.y", "$p1.y" ] }, 2 ] },
{ $pow: [ { $subtract: [ "$p2.x", "$p1.x" ] }, 2 ] }
]
}
}
}
}
])
该操作返回以下结果:
{ "_id" : 1, "distance" : 5.830951894845301 }
{ "_id" : 2, "distance" : 5 }
{ "_id" : 3, "distance" : 4 }