MongoDB $cos Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $cos?

$cos is a MongoDB aggregation expression that returns the cosine of an angle. The angle must be in radians. The result is a number between -1 and 1.

Remember
$cos = Math.cos for aggregation

{ $cos: <expression> }

input  → radians
output → cosine in [-1, 1]
degrees → wrap with $degreesToRadians first

null / missing → null
NaN → NaN
UsePrefer
Cosine of an angle$cos
Degrees → radians$degreesToRadians
Angle from a cosine value$acos

How to Use $cos in MongoDB

Start from radians (or convert degrees), then take cosine. Multiply by a length when you need a side.

  1. Choose an expression stage ($addFields or $project).
  2. If the angle is in degrees, convert with $degreesToRadians.
  3. Pass that radians expression to $cos.
  4. Optional: multiply by hypotenuse to get the adjacent side of a right triangle.
PieceRequired?Role
$cosYesCosine of a radians angle
ExpressionYesNumber in radians, field, or nested math
$degreesToRadiansNoConvert degree angles before $cos

Pseudocode

Pseudocode
for each document:
    x = evaluate(expression)   // radians
    if x is null or missing:
        result = null
    else if x is NaN:
        result = NaN
    else:
        result = cos(x)        // in [-1, 1]
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing cosine expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $cos: <expression> }
Input unitRadians
Output range-1 to 1
Degrees pattern{ $cos: { $degreesToRadians: <deg> } }
Triangle patternadjacent = cos(angle) × hypotenuse
Sample checkcos(60°) = 0.5

Live Preview

Watch $cos turn an angle into a cosine value. Degrees are converted to radians first (same idea as the examples).

Simulates $degreesToRadians then $cos (same idea as the mongosh examples below).

Result
angle = 60 °
radians ≈ 1.047198
$cos → 0.5

{ cosine: 0.5 }

Worked Walkthrough — 60° Triangle Side

Right triangle with hypotenuse 2 and angle A = 60°. Adjacent side = cos(A) × hypotenuse.

Calculation
Document:
  { angle_deg: 60, hypotenuse: 2 }

radians = degreesToRadians(60)
        ≈ 1.0472

cos(60°) = 0.5

adjacent = cos(A) × hypotenuse
         = 0.5 × 2
         = 1

Check: in a 30-60-90 triangle, sides are 1 : √3 : 2 ✓

MongoDB Examples

We use one right triangle with a 60° angle and hypotenuse 2. First we get the cosine, then we find the adjacent side. Insert the sample data once in mongosh.

Example 1 — Sample Data

Imagine one right triangle with angle 60° and hypotenuse 2. We save those as one document in a collection named trigonometry.

mongosh
db.trigonometry.insertOne({
  _id: 1,
  angle_deg: 60,
  hypotenuse: 2
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in trigonometry. Run find() to see it:

mongosh
db.trigonometry.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id (row number for this lesson)
angle_deg60Angle A in degrees (not radians yet)
hypotenuse2Longest side (opposite the right angle)
Picture
Right triangle (easy 30-60-90 style numbers):

        |\
        | \
   adj  |  \   2  (hypotenuse)
        |   \
        |    \
        |_____\
           ...
        angle A = 60°

  cos(A) = adjacent / hypotenuse
  adjacent = cos(A) × hypotenuse

How It Works

  1. Insert once. insertOne adds a single triangle document to trigonometry.
  2. MongoDB stores fields as written. angle_deg is 60 (degrees); hypotenuse is 2.
  3. find() shows the same shape. What you inserted is what you get back—ready for $cos in the next examples.

Example 2 — Cosine Value

Goal: convert 60° to radians, then take $cos to get the cosine (should be 0.5).

mongosh
db.trigonometry.aggregate([
  {
    $addFields: {
      cosine: {
        $cos: {
          $degreesToRadians: "$angle_deg"
        }
      }
    }
  }
]);

How It Works

  1. Read the stored angle. MongoDB already has angle_deg: 60 from Example 1.
  2. Convert units. $degreesToRadians turns 60° into about 1.047 radians.
  3. Take cosine. $cos returns about 0.5 (floating-point may show 0.5000000000000001).
  4. Keep all fields. $addFields adds cosine next to the original angle and hypotenuse.

Example 3 — Adjacent Side

Same triangle: multiply cosine by hypotenuse to get the adjacent side length (should be 1).

mongosh
db.trigonometry.aggregate([
  {
    $addFields: {
      adjacent: {
        $multiply: [
          {
            $cos: {
              $degreesToRadians: "$angle_deg"
            }
          },
          "$hypotenuse"
        ]
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using 60° and hypotenuse 2 from Example 1.
  2. Same cosine. cos(60°) ≈ 0.5 after the degrees→radians step.
  3. Scale by length. $multiply does 0.5 × 2 ≈ 1.
  4. Easy check. Adjacent side 1 with hypotenuse 2 matches the familiar 30-60-90 pattern.

Edge Cases & Pitfalls

Check these before using $cos in production pipelines.

units

Input is radians

Passing degrees directly gives the wrong cosine. Convert with $degreesToRadians first.

float

Floating-point noise

cos(60°) may print as 0.5000000000000001. Round when you need clean display values.

null

Null and missing become null

Missing fields return null, not an error. Handle them before trig if nulls are invalid in your data.

inverse

Need the angle? Use $acos

$cos goes angle → cosine. To go cosine → angle, use $acos.

Performance Notes

ApproachCostBest for
$cos alonePer-document mathAngles already in radians
$degreesToRadians + $cosStill O(docs)Human-friendly degree fields
+ $multiplyOne extra productTriangle side lengths

Trig expressions are cheap compared with large sorts or joins. Filter early with $match when only some documents need a cosine.

Key Takeaways

  • Role: cosine of an angle → value in [-1, 1].
  • Units: input must be radians.
  • Degrees: wrap with $degreesToRadians first.
  • Triangles: adjacent = cos(angle) × hypotenuse.

One line: $cos answers “what is the cosine of this angle?”—in radians in, value between -1 and 1 out.

Frequently Asked Questions

$cos returns the cosine of an angle. The input must be in radians, and the output is a number between -1 and 1. Use it inside aggregation expression stages such as $project and $addFields.
$cos expects radians. Convert degrees first with $degreesToRadians, or multiply by π/180 using $multiply and $divide.
$cos takes an angle (radians) and returns a cosine value. $acos takes a cosine value in [-1, 1] and returns an angle in radians. They are inverse operations.
$cos returns null when the input is null or the field is missing. If the argument is NaN, $cos returns NaN.
adjacent = cos(angle) × hypotenuse. Convert the angle to radians, pass it to $cos, then multiply by the hypotenuse.
Yes for the math. Think of $cos as MongoDB’s aggregation version of Math.cos—run it in the pipeline, not as a standalone find() filter.

Next: $cosh

Compute the hyperbolic cosine in an aggregation pipeline.

$cosh tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful