$atan2 (Two-Argument Arctangent)

Last updated: 2026-10-09

$atan2 (Two-Argument Arctangent)

$atan2 returns the bearing angle in radians from a y coordinate and an x coordinate, taking arguments in the order [y, x]. It handles all four quadrants correctly and is the key operation for converting Cartesian coordinates to polar form. It is used for direction math, navigation, and rotation in graphics, such as deriving a heading angle from a coordinate difference. A null or missing argument yields null, and the result is undefined when both y and x are zero. Unlike $atan it preserves quadrant information, returning values from -π to π.

CategoryMath
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

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

⚙️ Parameters

y coordinateThe y component; the first argument.
x coordinateThe x component; the second argument. Undefined when both are zero.

Returns:The bearing angle in radians; null when null or missing, undefined when both y and x are zero

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $atan2: bearing angle from x and y coordinates
db.points.aggregate([
  { $project: {
      bearing: { $atan2: ['$y', '$x'] }
  } }
])

Output:

{ '_id': 1, 'bearing': 0.7853981633974483 }
{ '_id': 2, 'bearing': -1.1071487177940904 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QWhat is the argument order of $atan2?
Ay first, then x; swapping them gives a wrong angle.
QHow do $atan2 and $atan differ?
A$atan2 takes two coordinate components and resolves the quadrant; $atan takes a single slope.
QWhat is the result range of $atan2?
AFrom -π to π radians, which is -180 to 180 degrees.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏