Introduction to MongoDB $cos Operator
$cos
is a mathematical operator in MongoDB used to calculate the cosine value of a given angle.
Syntax
The syntax of the $cos
operator is as follows:
{ $cos: <angle> }
Here, <angle>
is the value representing the angle and can be a number or an expression that evaluates to a number.
Use Cases
The $cos
operator is commonly used to calculate the values of trigonometric functions, particularly the cosine function. In MongoDB, it can be used in the $project
stage of the aggregation pipeline as well as in query operations.
Example
Suppose we have a collection trig
containing angle values with the following documents:
{ "_id": 1, "angle": 30 }
{ "_id": 2, "angle": 45 }
{ "_id": 3, "angle": 60 }
To calculate the cosine values of these angles, we can use the following aggregation pipeline:
db.trig.aggregate([
{ $project: { cos: { $cos: { $degreesToRadians: "$angle" } } } }
])
In the above pipeline, we first use the $degreesToRadians
operator to convert the angles to radians and pass it to the $cos
operator to calculate the cosine value. The output of the pipeline is as follows:
{ "_id": 1, "cos": 0.8660254037844386 }
{ "_id": 2, "cos": 0.7071067811865476 }
{ "_id": 3, "cos": 0.5000000000000001 }
Conclusion
The $cos
operator is a mathematical operator in MongoDB used to calculate the cosine value of a given angle. It can be used in the $project
stage of the aggregation pipeline as well as in query operations.