Introduction to MongoDB $atan2 Operator

$atan2 is a geospatial operator in MongoDB used to calculate the arctangent value between a given point and a reference point. It takes in the x and y coordinates as input and returns the arctangent value in radians. Unlike the $atan operator, $atan2 allows you to specify the x and y coordinates instead of using a single point.

Syntax

The syntax for the $atan2 operator is as follows:

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

Here, <y> and <x> represent the two coordinates for which the arctangent value is to be calculated.

Use cases

The $atan2 operator is typically used for geospatial queries and calculations. For example, you can use the $atan2 operator to calculate the direction between two geographical locations to determine the angle from one location to another.

Example

The following example demonstrates how to use the $atan2 operator to calculate the direction angle between two points. Suppose you have two geographical locations, one located at longitude -73.856077 and latitude 40.848447, and another located at longitude -73.926925 and latitude 40.692296. We can use the $atan2 operator to calculate the direction angle between these two locations as follows:

db.locations.aggregate([
  {
    $project: {
      angle: {
        $multiply: [
          {
            $atan2: [
              {
                $subtract: [
                  "$destination.coordinates[0]",
                  "$origin.coordinates[0]"
                ]
              },
              {
                $subtract: [
                  "$destination.coordinates[1]",
                  "$origin.coordinates[1]"
                ]
              }
            ]
          },
          180 / Math.PI
        ]
      }
    }
  }
])

The above example will compute the direction angle between destination and origin and store it in the angle field.

Conclusion

The $atan2 operator is a very useful geospatial operator in MongoDB that can help you calculate the direction angle between two geographical locations. If you need to perform geospatial queries or calculations in MongoDB, consider using the $atan2 operator.