MongoDB $sqrt Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Math Operations

What You’ll Learn

The $sqrt operator calculates the square root of a number in MongoDB aggregation pipelines. Use it for geometric calculations, data normalization, statistical analysis, and anywhere you need √x inside a query.

01

Square Root

√x from any field.

02

Syntax

One numeric expression.

03

$project Stage

Add computed fields.

04

Geometry

Distance and area.

05

Use Cases

Stats, normalization.

06

vs $pow

Clearer than 0.5.

Definition and Usage

In MongoDB’s aggregation framework, the $sqrt operator computes the square root of a numeric expression. For example, { $sqrt: 9 } returns 3, and { $sqrt: 25 } returns 5.

This is useful when you need mathematical operations inside a pipeline — such as computing distances from coordinate differences, deriving side lengths from areas, or transforming skewed numeric data.

💡
Beginner Tip

Think of $sqrt as MongoDB’s version of JavaScript’s Math.sqrt(). It works on non-negative numbers; negative inputs return null.

📝 Syntax

The $sqrt operator takes one numeric expression:

mongosh
{ $sqrt: <expression> }

Literal Examples

mongosh
{ $sqrt: 9 }
// Result: 3

{ $sqrt: 2 }
// Result: 1.4142135623730951

{ $sqrt: "$value" }
// Square root of the value field

Syntax Rules

  • $sqrt — returns the square root of the expression that follows.
  • <expression> — can be a field path, literal number, or nested numeric expression.
  • Use inside $project, $addFields, or $set.
  • Negative input — returns null (no real square root).
  • null input — returns null.
  • Zero input — returns 0.

💡 $sqrt vs $pow

$sqrt — dedicated square root: { $sqrt: "$x" }
$pow — general exponent: { $pow: [ "$x", 0.5 ] }
Both produce the same result for square roots; prefer $sqrt for readability.

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (math)
Syntax{ $sqrt: <expression> }
InputNon-negative number or numeric expression
OutputSquare root (number) or null
Negative inputnull
Common stages$project, $addFields, $set
Literal
{
  $sqrt: 16
}

Returns 4

Field
{
  $sqrt: "$value"
}

Field square root

Negative
{
  $sqrt: -4
}

Returns null

Nested
$sqrt: { $add: [...] }

Expression input

Examples Gallery

Compute square roots on document fields, calculate geometric distances, and compare with $pow.

📚 Basic Square Roots

Start with a numbers collection and compute square roots with $project.

Sample Input Documents

Suppose you have a numbers collection with a value field:

mongosh
[
  { "_id": 1, "value": 9 },
  { "_id": 2, "value": 16 },
  { "_id": 3, "value": 25 },
  { "_id": 4, "value": 2 }
]

Example 1 — Basic $sqrt on a Field

Use $project to add a sqrtValue field:

mongosh
db.numbers.aggregate([
  {
    $project: {
      value: 1,
      sqrtValue: { $sqrt: "$value" }
    }
  }
])

How It Works

  • Document 1: value is 9, so sqrtValue is 3.
  • Document 2: value is 16, so sqrtValue is 4.
  • Document 3: value is 25, so sqrtValue is 5.
  • Document 4: value is 2, so sqrtValue is approximately 1.414.

📈 Geometry and Statistics

Apply $sqrt to real-world distance and normalization problems.

Example 2 — Euclidean Distance (Pythagorean Theorem)

Calculate distance from coordinate differences using $sqrt with $add and $pow:

mongosh
db.points.aggregate([
  {
    $project: {
      name: 1,
      distance: {
        $sqrt: {
          $add: [
            { $pow: [ { $subtract: [ "$x2", "$x1" ] }, 2 ] },
            { $pow: [ { $subtract: [ "$y2", "$y1" ] }, 2 ] }
          ]
        }
      }
    }
  }
])

// (x1,y1)=(0,0), (x2,y2)=(3,4) → distance = 5

How It Works

Square the differences in x and y, add them, then take the square root. This is the classic √(dx² + dy²) formula for distance between two points.

Example 3 — Side Length from Area

If you store the area of a square, derive the side length:

mongosh
db.plots.aggregate([
  {
    $project: {
      plotId: 1,
      areaSqM: 1,
      sideLength: { $sqrt: "$areaSqM" }
    }
  }
])

// areaSqM: 144 → sideLength: 12
// areaSqM: 81  → sideLength: 9

How It Works

For a square, side = √area. This pattern works whenever a stored value is the square of the quantity you need.

Example 4 — Standard Deviation Scaling

Square roots can reduce skew in variance-based calculations. A simplified normalization step:

mongosh
db.metrics.aggregate([
  {
    $project: {
      sensor: 1,
      variance: 1,
      stdDevApprox: { $sqrt: "$variance" }
    }
  }
])

How It Works

Standard deviation is the square root of variance. If variance is already stored, $sqrt gives you the spread measure directly.

Bonus — $sqrt vs $pow with 0.5

Both approaches compute the same square root; $sqrt reads more clearly:

mongosh
db.numbers.aggregate([
  {
    $project: {
      value: 1,
      viaSqrt: { $sqrt: "$value" },
      viaPow:  { $pow: [ "$value", 0.5 ] }
    }
  }
])

How It Works

Raising to the power of 0.5 is mathematically equivalent to a square root. Prefer $sqrt when that is all you need.

🚀 Use Cases

  • Geometric calculations — compute distances, dimensions, and side lengths from squared values.
  • Data normalization — transform squared or variance-based metrics back to original scale.
  • Statistical analysis — derive standard deviation from variance stored in documents.
  • Sensor and IoT data — convert power or energy readings that were stored squared.

🧠 How $sqrt Works

1

MongoDB reads the expression

The pipeline evaluates the input — a field like "$value" or a numeric expression.

Input
2

$sqrt validates the value

Non-negative numbers proceed. Negative numbers return null; null input stays null.

Validate
3

The square root is computed

MongoDB returns the principal (non-negative) square root as a floating-point number when needed.

Compute
=

Numeric result

The value is stored in the field you define in $project or $addFields.

Conclusion

The $sqrt operator is a straightforward math tool in MongoDB aggregation pipelines. It computes square roots for geometric calculations, statistical transforms, and data normalization.

For beginners, remember: wrap any non-negative numeric expression in { $sqrt: ... } inside a stage like $project. Next in the series: $strcasecmp.

💡 Best Practices

✅ Do

  • Use $sqrt for readability when you only need a square root
  • Combine with $pow and $add for distance formulas
  • Validate that inputs are non-negative before applying $sqrt
  • Handle null inputs with $ifNull when fields may be missing
  • Round results with $round when displaying to users

❌ Don’t

  • Expect a real result from negative numbers — MongoDB returns null
  • Confuse $sqrt with $split (string vs math operator)
  • Use $sqrt as a query filter outside expression stages
  • Assume it converts non-numeric strings to numbers
  • Forget that irrational roots (like √2) return floating-point decimals

Key Takeaways

Knowledge Unlocked

Five things to remember about $sqrt

Use these points when writing your next aggregation pipeline.

5
Core concepts
📝 02

Simple Syntax

{ $sqrt: expr }

Syntax
🛠 03

Negative → null

No real root.

Edge case
📐 04

Geometry

Distance & area.

Use case
05

vs $pow 0.5

Prefer $sqrt.

Compare

❓ Frequently Asked Questions

$sqrt returns the square root of a numeric expression. For example, { $sqrt: 9 } returns 3, and { $sqrt: "$value" } computes the square root of a field. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $sqrt: <expression> }. The expression can be a field reference like "$value", a literal number, or another numeric expression such as { $add: [ "$a", "$b" ] }.
MongoDB returns null when the input is negative, because square roots of negative numbers are not real numbers. Use $abs or validate data first if negative values are possible.
$sqrt is dedicated to square roots: { $sqrt: "$x" }. You can also use { $pow: [ "$x", 0.5 ] } for the same result, but $sqrt is clearer and easier to read.
$sqrt returns null when the input is null. It does not throw an error. Use $ifNull to provide a default when the field may be missing.

Continue the Operator Series

Move on to $strcasecmp for case-insensitive string comparison, or review $pow for exponent math.

Next: $strcasecmp →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful