MongoDB $atan2 Operator

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

What Is $atan2?

$atan2 is a MongoDB aggregation expression that returns the angle from the positive x-axis to the point (x, y). It takes two arguments (y then x) and picks the correct quadrant. Results are in radians (about -π to π).

Remember
$atan2 = Math.atan2 for aggregation

{ $atan2: [ <y>, <x> ] }

order  → y first, then x (same as JS)
output → radians (−π … π), correct quadrant
degrees → wrap with $radiansToDegrees

null / missing (either arg) → null
NaN → NaN
UsePrefer
Angle from separate x and y$atan2
Angle from a single slope$atan
Radians → degrees$radiansToDegrees

How to Use $atan2 in MongoDB

Pass y and x as a two-element array, then convert units if needed.

  1. Choose an expression stage ($addFields or $project).
  2. Build { $atan2: [ "$y", "$x" ] } — remember y before x.
  3. Read the result in radians (full range, all quadrants).
  4. Optionally wrap with $radiansToDegrees for a degree result.
PieceRequired?Role
$atan2YesTwo-arg inverse tangent → radians
[ y, x ]YesArray of two numeric expressions
$radiansToDegreesNoConvert output when you want degrees

Pseudocode

Pseudocode
for each document:
    y = evaluate(yExpression)
    x = evaluate(xExpression)
    if y or x is null or missing:
        result = null
    else if y or x is NaN:
        result = NaN
    else:
        result = atan2(y, x)   // radians, correct quadrant
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing two-argument arc-tangent expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $atan2: [ <y>, <x> ] }
Argument ordery first, then x
RangeAbout -π to π radians
Degrees pattern{ $radiansToDegrees: { $atan2: [y, x] } }
vs $atan$atan2 keeps quadrant; $atan(y/x) does not
Sample checkatan2(3, 4) ≈ 36.87°

Live Preview

Watch $atan2(y, x) return a quadrant-correct angle in radians and degrees.

Simulates $atan2 then $radiansToDegrees (same idea as the mongosh examples below).

Result
y = 3, x = 4
$atan2(y, x) → 0.643501 rad
$radiansToDegrees → 36.869898 °

{ angle_rad: 0.643501, angle_deg: 36.869898 }

Worked Walkthrough — Point (4, 3)

Same idea as a 3-4-5 triangle: point at x = 4, y = 3. We want the angle from the positive x-axis to that point.

Calculation
Document:
  { x: 4, y: 3 }

$atan2(y, x) = atan2(3, 4)
             ≈ 0.6435 radians

$radiansToDegrees(...) ≈ 36.87 degrees

Why not $atan(y/x)?
  atan(3/4) also ≈ 36.87° here —
  but if x were negative, $atan2 keeps the right quadrant
  while $atan(y/x) would not.

MongoDB Examples

We store one point (x: 4, y: 3). First we get the angle in radians, then convert to degrees. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one point on a plane: x = 4, y = 3 (the same sides as a 3-4-5 triangle). We save it as one document in a collection named points.

mongosh
db.points.insertOne({
  _id: 1,
  x: 4,
  y: 3
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in points. Run find() to see it:

mongosh
db.points.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id (row number for this lesson)
x4Horizontal coordinate (adjacent side)
y3Vertical coordinate (opposite side)
Picture
Point on a plane:

  y
  ^
  |     • (4, 3)
  |    /
  |   /  angle from +x axis
  |  /
  | /
  +------------> x
  O

$atan2(y, x) = $atan2(3, 4)
Remember: y comes first in the array.

How It Works

  1. Insert once. insertOne adds a single point document to points.
  2. MongoDB stores fields as written. x and y are just numbers: 4 and 3.
  3. find() shows the same shape. What you inserted is what you get back—ready for $atan2 in the next examples.

Example 2 — Angle in Radians

Goal: compute the angle from the positive x-axis using $atan2(y, x).

mongosh
db.points.aggregate([
  {
    $addFields: {
      angle_rad: {
        $atan2: ["$y", "$x"]
      }
    }
  }
]);

How It Works

  1. Read the stored point. MongoDB already has x: 4 and y: 3 from Example 1.
  2. Pass y then x. $atan2: ["$y", "$x"] → atan2(3, 4).
  3. Get radians. The result is about 0.6435 (same angle as atan(3/4) in this quadrant).
  4. Keep all fields. $addFields adds angle_rad next to x and y—nothing is deleted.

Example 3 — Angle in Degrees

Same point, but wrap $atan2 with $radiansToDegrees for a more familiar unit.

mongosh
db.points.aggregate([
  {
    $addFields: {
      angle_deg: {
        $radiansToDegrees: {
          $atan2: ["$y", "$x"]
        }
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using point (4, 3) from Example 1.
  2. Same $atan2 call. atan2(3, 4) gives radians (~0.6435).
  3. Convert units. $radiansToDegrees turns that into about 36.87°.
  4. Easy check. In a 3-4-5 triangle, the smaller acute angle is about 37°—so 36.87° looks right.

Edge Cases & Pitfalls

Check these before using $atan2 in production pipelines.

order

y comes before x

Writing [$x, $y] by habit flips the axes. Always use { $atan2: ["$y", "$x"] }.

units

Output is radians

Do not treat the raw result as degrees. Convert with $radiansToDegrees when your report expects °.

quad

Prefer over $atan(y/x) for points

A single slope loses quadrant info and breaks when x is zero. Use $atan2 for plane angles.

null

Either null makes the result null

If x or y is missing/null, $atan2 returns null. Validate coordinates before trig if needed.

Performance Notes

ApproachCostBest for
$atan2 alonePer-document mathAngles from stored x/y fields
+ $radiansToDegreesOne extra conversionHuman-readable degree reports
$atan(y/x) insteadSimilar cost, worse correctnessAvoid when quadrants matter

Trig expressions are cheap compared with large sorts or joins. Filter early with $match when only some documents need an angle.

Key Takeaways

  • Role: angle from +x axis to point (x, y).
  • Order: { $atan2: [y, x] } — y first.
  • Quadrants: safer than $atan(y/x) for plane points.
  • Degrees: wrap with $radiansToDegrees.

One line: $atan2 answers “what angle is this point from the +x axis?”—in radians, with the correct quadrant.

Frequently Asked Questions

$atan2 returns the angle in radians from the positive x-axis to the point (x, y). It takes two arguments—y then x—and returns the correct angle in all four quadrants (about -π to π).
MongoDB matches JavaScript Math.atan2(y, x). Putting y first lets the operator pick the right quadrant, including when x is zero.
Use $atan2 when you have separate x and y and need full quadrant accuracy. Use $atan when you already have a single slope (y/x) and do not need four-quadrant results.
$atan2 returns radians. Convert with $radiansToDegrees, or multiply by 180/π using $multiply and $divide.
If either argument is null or missing, $atan2 returns null. If an argument is NaN, the result is NaN.
Yes for the math and argument order. Think of $atan2 as MongoDB’s aggregation version of Math.atan2(y, x)—run it in the pipeline, not as a standalone find() filter.

Next: $atanh

Compute the inverse hyperbolic tangent in an aggregation pipeline.

$atanh 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