定义
行为
默认返回类型是 double。如果至少有一个操作数是 decimal,则返回类型为 decimal。
如果参数解析为 null 的值或引用了缺失的字段,$sqrt 返回 null。如果参数解析为 NaN,$sqrt 会返回 NaN。
$sqrt 负数错误。
例子 | 结果 |
|---|---|
|
|
|
|
|
|
例子
集合 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} } ] )
以下示例使用 $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 }