MongoDB $sqrt Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $sqrt?

$sqrt is a MongoDB aggregation expression that returns the square root of a non-negative number. Input must be ≥ 0. Negative values make the pipeline fail.

Remember
$sqrt = Math.sqrt for aggregation

{ $sqrt: <expression> }

input  → must be ≥ 0
output → double (or decimal if input is decimal)

√9 → 3
√0 → 0
null / missing → null
negative → pipeline error
UsePrefer
Square root of a number$sqrt
x raised to any power$pow
Force non-negative before root$abs (when that matches your math)
Side length from area (square)$sqrt("$area")

How to Use $sqrt in MongoDB

Pass a non-negative number (or an expression that produces one), then use the result in further math if needed.

  1. Choose an expression stage ($addFields or $project).
  2. Ensure the argument is ≥ 0 (filter with $match or guard with $cond).
  3. Pass that expression to $sqrt.
  4. For distance / hypotenuse, build a² + b² first, then take $sqrt.
PieceRequired?Role
$sqrtYesSquare root → non-negative result
ExpressionYesNumber ≥ 0, field, or nested math
$pow / $addNoBuild sums of squares before the root

Pseudocode

Pseudocode
for each document:
    x = evaluate(expression)
    if x is null or missing:
        result = null
    else if x is NaN:
        result = NaN
    else if x < 0:
        error  // aggregation fails
    else:
        result = sqrt(x)
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing square-root expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $sqrt: <expression> }
Domainx ≥ 0
Return typeDouble by default (decimal if input is decimal)
Hypotenuse pattern$sqrt({ $add: [ { $pow: [a, 2] }, { $pow: [b, 2] } ] })
Alt form{ $pow: [ "$x", 0.5 ] } (prefer $sqrt for clarity)
Sample check$sqrt(25) = 5; 3-4-5 triangle hypotenuse = 5

Live Preview

Watch $sqrt turn a non-negative number into its square root. Try perfect squares and a non-integer root.

Simulates $sqrt (same idea as the mongosh examples below).

Result
x = 25
$sqrt(x) → 5

{ root: 5 }

Worked Walkthrough — Side from Area

A square room has area 25. Side length is the square root of the area.

Calculation
Document:
  { room: "A", area: 25 }

side = √area
     = √25
     = 5

$sqrt("$area") → 5

Check: 5 × 5 = 25 ✓

MongoDB Examples

We use a square room (area → side) and a 3-4-5 right triangle (legs → hypotenuse). Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one square room with area 25, and one right triangle with legs 3 and 4. We save them in shapes.

mongosh
db.shapes.insertMany([
  { _id: 1, kind: "square", area: 25 },
  { _id: 2, kind: "triangle", a: 3, b: 4 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in shapes. Run find() to see them:

mongosh
db.shapes.find()

Read those documents like this:

Field in MongoDBValuePlain English
area25Square area (side × side)
a, b3, 4Legs of a right triangle
Goalside / hypotenuseUse $sqrt in the next examples
Picture
Square (area 25):
  side = √25 = 5

Right triangle (3-4-5):
        |\
      3 | \  hypotenuse
        |  \
        |___\
          4

hypotenuse = √(3² + 4²) = √(9 + 16) = √25 = 5

How It Works

  1. Insert once. insertMany adds the square and triangle to shapes.
  2. Numbers stay as written. Area and legs are plain numbers ready for math.
  3. find() shows the same shape. What you inserted is what you get back—ready for $sqrt next.

Example 2 — Side Length from Area

Goal: for the square document, compute side length with $sqrt("$area").

mongosh
db.shapes.aggregate([
  { $match: { kind: "square" } },
  {
    $addFields: {
      side: { $sqrt: "$area" }
    }
  }
]);

How It Works

  1. Filter first. $match keeps only the square document.
  2. Read area. MongoDB already has area: 25 from Example 1.
  3. Take the root. $sqrt(25) returns 5.
  4. Keep all fields. $addFields adds side next to area.

Example 3 — Hypotenuse (3-4-5)

Same collection: build a² + b², then take the square root to get the hypotenuse.

mongosh
db.shapes.aggregate([
  { $match: { kind: "triangle" } },
  {
    $addFields: {
      hypotenuse: {
        $sqrt: {
          $add: [
            { $pow: ["$a", 2] },
            { $pow: ["$b", 2] }
          ]
        }
      }
    }
  }
]);

How It Works

  1. Same stored triangle. Legs are still 3 and 4 from Example 1.
  2. Square each leg. $pow gives 9 and 16.
  3. Add the squares. $add yields 25.
  4. Take the root. $sqrt(25) is 5—the classic 3-4-5 hypotenuse.

Edge Cases & Pitfalls

Check these before using $sqrt in production pipelines.

domain

Negatives fail the pipeline

Unlike JavaScript Math.sqrt(-1) → NaN, MongoDB errors on negative input. Filter or guard first.

null

Null and missing become null

Missing fields return null, not an error. Handle them before roots if nulls are invalid in your data.

vs $pow

Prefer $sqrt over $pow(..., 0.5)

$pow works for any exponent. For square roots, $sqrt is clearer for readers and reviews.

zero

√0 is valid

$sqrt(0) returns 0. Zero is in the allowed domain.

Performance Notes

ApproachCostBest for
$sqrt alonePer-document mathStored areas, variances, scores
$pow + $add + $sqrtStill O(docs)Distance / hypotenuse formulas
$match then $sqrtFewer docs to computeOnly some rows need a root

Math expressions are cheap compared with large sorts or joins. Filter early with $match when only some documents need a square root.

Key Takeaways

  • Role: square root of a non-negative number.
  • Domain: argument must be ≥ 0.
  • Geometry: $sqrt(a² + b²) for hypotenuse.
  • Negatives: pipeline error — not NaN.

One line: $sqrt answers “which non-negative number, squared, gives this value?”

Frequently Asked Questions

$sqrt returns the square root of a non-negative number as a double (or decimal if you use decimal input). Use it inside aggregation expression stages such as $project and $addFields.
Use { $sqrt: <expression> }. The expression can be a field like "$area", a literal such as 25, or nested math like { $add: [ "$a", "$b" ] }.
The aggregation fails with an error. Square roots of negative numbers are not supported as real values. Filter or clamp with $abs / $cond before calling $sqrt when negatives are possible.
$sqrt is the clear form for square roots. { $pow: [ "$x", 0.5 ] } can produce the same idea, but $sqrt is easier to read and intent is obvious.
$sqrt returns null when the input is null or the field is missing. If the argument is NaN, $sqrt returns NaN.
Yes for the math on non-negative numbers. Think of $sqrt as MongoDB’s aggregation version of Math.sqrt—run it in the pipeline, not as a standalone find() filter. Unlike Math.sqrt(-1) → NaN, MongoDB errors on negatives.

Next: $strcasecmp

Compare two strings case-insensitively in an aggregation pipeline.

$strcasecmp tutorial →

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.

9 people found this page helpful