$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 π.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $atan2: [ <y>, <x> ] }
⚙️ Parameters
| y coordinate | The y component; the first argument. |
|---|---|
| x coordinate | The 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
- Arguments are y first, then x — do not swap them
- Results span -π to π, distinguishing all four quadrants
- The result is undefined when both y and x are zero; filter that case first