平方根(聚合)
定义
行为
默认返回类型是 double。如果至少有一个操作数是 decimal,则返回类型为 decimal。
如果参数解析为 null 或引用的域不存在,则 $sqrt 返回 null。如果参数解析为 NaN,则 $sqrt 返回 NaN。
$sqrt 在负数上会出错。
示例 | 结果 |
|---|---|
{ $sqrt: 25 } | 5 |
{ $sqrt: 30 } | 5.477225575051661 |
{ $sqrt: null } | null |
示例
包含以下文档的集合 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 }