$sqrt (aggregation)

Definition

  • $sqrt

New in version 3.2.

Calculates the square root of a positive number and returns theresult as a double.

$sqrt has the following syntax:

  1. { $sqrt: <number> }

The argument can be any valid expression as long as it resolves to a _non-negative_number. For more informationon expressions, see Expressions.

Behavior

If the argument resolves to a value of null or refers to a field that ismissing, $sqrt returns null. If the argument resolves toNaN, $sqrt returns NaN.

$sqrt errors on negative numbers.

ExampleResults
{ $sqrt: 25 }5
{ $sqrt: 30 }5.477225575051661
{ $sqrt: null }null

Example

A collection points contains the following documents:

  1. { _id: 1, p1: { x: 5, y: 8 }, p2: { x: 0, y: 5} }
  2. { _id: 2, p1: { x: -2, y: 1 }, p2: { x: 1, y: 5} }
  3. { _id: 3, p1: { x: 4, y: 4 }, p2: { x: 4, y: 0} }

The following example uses $sqrt to calculate thedistance between p1 and p2:

  1. db.points.aggregate([
  2. {
  3. $project: {
  4. distance: {
  5. $sqrt: {
  6. $add: [
  7. { $pow: [ { $subtract: [ "$p2.y", "$p1.y" ] }, 2 ] },
  8. { $pow: [ { $subtract: [ "$p2.x", "$p1.x" ] }, 2 ] }
  9. ]
  10. }
  11. }
  12. }
  13. }
  14. ])

The operation returns the following results:

  1. { "_id" : 1, "distance" : 5.830951894845301 }
  2. { "_id" : 2, "distance" : 5 }
  3. { "_id" : 3, "distance" : 4 }