Introduction to MongoDB $sin Operator

$sin is a mathematical operator in MongoDB that calculates the sine value of a given angle. It can be used as an expression in the $project stage of an aggregation pipeline.

Syntax

The syntax of the $sin operator is as follows:

{ $sin: <expression> }

Here, <expression> is an expression that represents an angle, which can be a number, a field name, or another numerical expression.

Use Case

The $sin operator is typically used in the $project stage of an aggregation pipeline to calculate the sine value of a given angle and add the result to the output document. For example, you can use the $sin operator to calculate the angle of an employee and add the result to the output document.

Example

Assume that there is an employees collection that contains the name and angle fields for each employee. Now, we want to calculate the sine value of each employee’s angle and add the result to the output document. We can use the following aggregation pipeline to accomplish this:

db.employees.aggregate([
  {
    $project: {
      name: 1,
      angle: 1,
      sinValue: { $sin: { $degreesToRadians: "$angle" } }
    }
  }
])

In the above aggregation pipeline, we first select the name and angle fields and use the $sin operator to calculate the sine value of the angle. We use the $degreesToRadians operator to convert the angle from degrees to radians and then save the result to the sinValue field.

Assuming that the employees collection contains the following documents:

{ "name": "Alice", "angle": 30 }
{ "name": "Bob", "angle": 45 }
{ "name": "Charlie", "angle": 60 }

After running the above aggregation pipeline, the output is as follows:

{ "name": "Alice", "angle": 30, "sinValue": 0.5 }
{ "name": "Bob", "angle": 45, "sinValue": 0.7071067811865475 }
{ "name": "Charlie", "angle": 60, "sinValue": 0.8660254037844386 }

As you can see, each document contains the sinValue field, which represents the sine value of the angle.

Conclusion

The $sin operator is a mathematical operator in MongoDB that calculates the sine value. It is typically used in the $project stage of an aggregation pipeline to calculate the sine value of a given angle and add the result to the output document. With the $sin operator, you can easily perform calculations on angles and use the results for subsequent aggregation operations.