Introduction to MongoDB $radiansToDegrees Operator

$radiansToDegrees is an aggregation operator in MongoDB, used to convert angles in radians to angles in degrees.

Syntax

The syntax of the $radiansToDegrees operator is as follows:

{ $radiansToDegrees: <expression> }

Here, <expression> is the angle value expression to be converted, which can be a field reference, constant, or expression.

Use Cases

In MongoDB aggregation operations, it is sometimes necessary to convert angles from radians to degrees for better analysis and processing. In this case, the $radiansToDegrees operator can be used to achieve this.

Example

Assume that there is a data collection students with the following data:

{ "_id" : 1, "name" : "Alice", "score" : 80, "angle" : 1.047 }
{ "_id" : 2, "name" : "Bob", "score" : 90, "angle" : 2.094 }
{ "_id" : 3, "name" : "Cathy", "score" : 85, "angle" : 3.142 }
{ "_id" : 4, "name" : "David", "score" : 70, "angle" : 0.524 }

Now suppose you want to query each student’s ID, name, score, and angle value in degrees. This can be achieved using the following aggregation query:

db.students.aggregate([
  {
    $project: {
      _id: 1,
      name: 1,
      score: 1,
      degree: { $radiansToDegrees: "$angle" }
    }
  }
])

After running the above aggregation operation, the following result is obtained:

{ "_id" : 1, "name" : "Alice", "score" : 80, "degree" : 60 }
{ "_id" : 2, "name" : "Bob", "score" : 90, "degree" : 120 }
{ "_id" : 3, "name" : "Cathy", "score" : 85, "degree" : 180 }
{ "_id" : 4, "name" : "David", "score" : 70, "degree" : 30 }

It can be seen that a field named degree is added to the query results, which stores the angle value in degrees.

Conclusion

The $radiansToDegrees operator can conveniently convert angles in radians to angles in degrees, making it easier to analyze and process angles in aggregation operations.