MongoDB $atan2 Operator

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 4 Examples
Trigonometry

What You’ll Learn

The $atan2 operator returns the angle (in radians) from the positive x-axis to a point defined by (x, y) coordinates. It fixes the quadrant limitations of $atan and works even when x is zero.

01

Two Arguments

Takes y and x separately.

02

Syntax

[y, x] array form.

03

All Quadrants

Full -π to π range.

04

y Before x

Argument order matters.

05

Use Cases

Vectors, navigation, maps.

06

x = 0 Safe

No division by zero.

Definition and Usage

In MongoDB’s aggregation framework, the $atan2 operator computes the arc tangent of y/x while using the signs of both y and x to determine the correct quadrant. For example, $atan2(1, 1) returns approximately 0.785 rad (45°), while $atan2(1, -1) returns approximately 2.356 rad (135°) — same slope, different quadrant.

💡
Beginner Tip

Think of $atan2 as MongoDB’s version of Math.atan2(y, x). The y value comes first, then x. This order is easy to mix up, so double-check your pipeline.

📝 Syntax

The $atan2 operator takes two numeric expressions in an array:

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

Syntax Rules

  • $atan2 — returns the angle in radians from the positive x-axis to the point (x, y).
  • <y> — the y-coordinate (first argument).
  • <x> — the x-coordinate (second argument).
  • Output range is to π radians (approximately -3.14 to 3.14).
  • Works when x = 0 (returns ±π/2 depending on the sign of y).
  • If either argument is null, the result is null.

⚠️ Argument Order: y First, x Second

The most common mistake is swapping the arguments. MongoDB uses the same order as JavaScript:

Correct: { $atan2: ["$y", "$x"] }
Wrong: { $atan2: ["$x", "$y"] } (swapped!)
$atan2(1, 1)0.785 rad (45°)
$atan2(1, -1)2.356 rad (135°)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (trigonometry)
Syntax{ $atan2: [<y>, <x>] }
Argument ordery first, then x
Output unitRadians (range -π to π)
Common stages$project, $addFields, $set
Example
{
  $atan2: [1, 1]
}

≈ 0.785 rad (45°)

Fields
{
  $atan2: ["$y", "$x"]
}

Angle from coordinates

x = 0
{
  $atan2: [3, 0]
}

≈ 1.571 rad (90°)

Null input
{
  $atan2: [null, 1]
}

Returns null

Examples Gallery

Compute full-quadrant angles from x and y coordinates using $atan2 in aggregation pipelines.

📚 Coordinates to Angle

Use a vectors collection with x and y components and compute the correct quadrant angle with $project.

Sample Input Documents

Suppose you have a vectors collection with x and y components:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "x": 3,  "y": 4 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "x": -2, "y": 2 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "x": 1,  "y": -1 }
]

Example 1 — Full-Quadrant Vector Angles

Calculate the angle (in radians) for each vector. Note that y comes first in the array:

mongosh
db.vectors.aggregate([
  {
    $project: {
      x: 1,
      y: 1,
      angleRadians: { $atan2: ["$y", "$x"] },
      angleWithAtan: {
        $atan: { $divide: ["$y", "$x"] }
      }
    }
  }
])

How It Works

  • Document 1: Quadrant I — both operators agree: 0.927 rad (53°).
  • Document 2: Quadrant II — $atan2 returns 2.356 rad (135°), but $atan gives -0.785 (wrong quadrant).
  • Document 3: Quadrant IV — both agree: -0.785 rad (-45°).

📈 Practical Patterns

Handle edge cases, convert to degrees, and apply to navigation-style data.

Example 2 — When x Is Zero

$atan2 handles vertical vectors without division errors:

mongosh
db.vectors.aggregate([
  {
    $project: {
      x: 1,
      y: 1,
      angleRadians: { $atan2: ["$y", "$x"] }
    }
  }
])

// Sample documents:
// { x: 0, y: 3 }   → atan2(3, 0)  ≈ 1.571 rad (90°, straight up)
// { x: 0, y: -2 }  → atan2(-2, 0) ≈ -1.571 rad (-90°, straight down)
// { x: 0, y: 0 }   → atan2(0, 0)  = 0 (origin point)

How It Works

With $atan({ $divide: ["$y", "$x"] }), dividing by zero fails or returns null. $atan2 avoids division entirely and returns the correct angle.

Example 3 — Convert Radians to Degrees (Bearing)

Convert the angle to degrees for navigation or mapping dashboards:

mongosh
db.vectors.aggregate([
  {
    $project: {
      x: 1,
      y: 1,
      bearingRadians: { $atan2: ["$y", "$x"] },
      bearingDegrees: {
        $multiply: [
          { $atan2: ["$y", "$x"] },
          { $divide: [ 180, 3.141592653589793 ] }
        ]
      }
    }
  }
])

How It Works

The formula is degrees = radians × (180 / π). Negative degrees indicate angles below the x-axis.

Example 4 — Direction Between Two Points

Compute the bearing from one location to another by subtracting coordinates first:

mongosh
db.routes.aggregate([
  {
    $project: {
      from: 1,
      to: 1,
      deltaX: { $subtract: ["$to.x", "$from.x"] },
      deltaY: { $subtract: ["$to.y", "$from.y"] }
    }
  },
  {
    $project: {
      from: 1,
      to: 1,
      directionRadians: {
        $atan2: ["$deltaY", "$deltaX"]
      }
    }
  }
])

How It Works

Subtract the starting point from the destination to get deltaX and deltaY, then pass them to $atan2 as [deltaY, deltaX]. This pattern is common in navigation and game development pipelines.

🚀 Use Cases

  • Geospatial analysis — calculate angles or bearings between coordinate pairs.
  • Navigation systems — determine direction for route planning and guidance.
  • Mapping applications — compute orientations for displaying features on maps.
  • Robotics and games — rotate sprites or agents toward a target point using deltaX and deltaY.

🧠 How $atan2 Works

1

MongoDB reads y and x

The pipeline evaluates both arguments — typically fields like "$y" and "$x" or computed deltas.

Input
2

$atan2 determines the quadrant

Using both signs, MongoDB computes the full angle from -π to π without dividing y by x.

Transform
3

The result is stored in the pipeline

The angle is written to the field you define in $project or $addFields.

Output
=

Correct quadrant angle

Use the radians directly or convert to degrees for bearings and headings.

Conclusion

The $atan2 operator is the right choice when you have separate x and y values and need the correct angle in all four quadrants. It avoids division-by-zero problems and fixes the quadrant ambiguity that $atan cannot resolve on its own.

For beginners, remember: y comes first, output is in radians, and always prefer $atan2 over $atan(y/x) when both coordinates are available.

💡 Best Practices

✅ Do

  • Pass arguments as [y, x] — y first, x second
  • Use $atan2 when you have separate coordinate values
  • Subtract points first to get deltas for direction calculations
  • Convert to degrees with $multiply and $divide when needed
  • Compare side-by-side with $atan to verify quadrant behavior

❌ Don’t

  • Swap the argument order to [x, y]
  • Use $atan(y/x) when quadrant accuracy matters
  • Assume output is in degrees
  • Confuse $atan2 with $atan (single argument)
  • Use latitude/longitude directly as x/y without understanding the coordinate system

Key Takeaways

Knowledge Unlocked

Five things to remember about $atan2

Use these points when working with two-argument angles in MongoDB.

5
Core concepts
📝 02

y Before x

{ $atan2: [y, x] }

Syntax
📏 03

Full Quadrants

Range -π to π.

Domain
🛠 04

x = 0 Safe

No division needed.

Edge case
05

Beats $atan

Correct quadrant angles.

Tip

❓ Frequently Asked Questions

$atan2 returns the angle (in radians) from the positive x-axis to the point (x, y). Unlike $atan, it uses two separate arguments and returns the correct angle in all four quadrants.
The syntax is { $atan2: [ <y>, <x> ] }. The first element is the y-coordinate (numerator) and the second is the x-coordinate (denominator). Both can be field references or expressions.
MongoDB follows the same convention as JavaScript Math.atan2(y, x). The y argument comes first so the operator can determine the correct quadrant even when x is zero.
Use $atan2 whenever you have separate x and y values and need the full angle from -π to π. Use $atan only when you already have a single slope ratio (y/x) and quadrant precision is not required.
$atan2 returns radians (range -π to π). To convert to degrees, multiply the result by 180 and divide by pi using $multiply and $divide.

Continue the Math Operator Series

Move on to $atanh for inverse hyperbolic tangent, or review $atan for single-argument arc tangent.

Next: $atanh →

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