Introduction to MongoDB $degreesToRadians Operator

In MongoDB, the $degreesToRadians operator is used to convert angle values from degrees to radians. It can be used in aggregation pipelines to convert angles to radians before performing other mathematical calculations.

Syntax

The syntax for the $degreesToRadians operator is as follows:

{ $degreesToRadians: <angle> }

Here, <angle> is the angle value to be converted to radians, which can be a number or an expression that points to a field containing an angle value.

Use Cases

The $degreesToRadians operator is commonly used in aggregation pipelines for geospatial calculations. Geospatial calculations require radians as the unit of measurement, whereas degrees are commonly used. Therefore, it is necessary to convert degrees to radians before performing geospatial calculations.

Example

Suppose we have a collection called locations that contains documents, each of which includes a subdocument called location that contains an array called coordinates, which includes two values representing longitude and latitude in degrees. We want to convert these degree values to radians.

We can use the following aggregation pipeline to accomplish this:

db.locations.aggregate([
  {
    $project: {
      location: 1,
      coordinatesInRadians: {
        $map: {
          input: "$location.coordinates",
          as: "coord",
          in: {
            $degreesToRadians: "$$coord"
          }
        }
      }
    }
  }
])

In this aggregation pipeline, we use the $project stage to keep the location subdocument and the coordinates array, and then use the $map operator to convert each value in the array to radians. Finally, we get a new field called coordinatesInRadians that contains the converted radian values.

Suppose our collection contains the following two documents:

{
    "location" : {
        "coordinates" : [ -122.4194, 37.7749 ]
    }
}
{
    "location" : {
        "coordinates" : [ -73.935242, 40.730610 ]
    }
}

After running the above aggregation pipeline, we get the following results:

{
  "location" : {
    "coordinates" : [ -122.4194, 37.7749 ]
  },
  "coordinatesInRadians" : [
    -2.136317242832307,
    0.6594203739402457
  ]
}
{
  "location" : {
    "coordinates" : [ -73.935242, 40.730610 ]
  },
  "coordinatesInRadians" : [
    -1.2890541868241255,
    0.7117995435276495
  ]
}

Conclusion

In this article, we introduced the $degreesToRadians operator in MongoDB, which can be used to convert angle values to radians.