MongoDB $cos Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Trigonometry

What You’ll Learn

The $cos operator computes the cosine of an angle in MongoDB aggregation pipelines. Use it for geometry, signal processing, and physics calculations when your data stores angles in radians.

01

Cosine

Angle → ratio.

02

Syntax

One expression inside $cos.

03

Radians

Input must be radians.

04

Output Range

Always -1 to 1.

05

Use Cases

Geometry, signals, physics.

06

vs $acos

Forward vs inverse.

Definition and Usage

In MongoDB’s aggregation framework, the $cos operator returns the cosine of a numeric angle expressed in radians. For example, cos(0) = 1 and cos(π/2) = 0. The result is always between -1 and 1.

💡
Beginner Tip

$cos expects radians, not degrees. If your data stores degrees, convert first with $multiply and $divide before applying $cos.

📝 Syntax

The $cos operator takes one numeric expression (angle in radians):

mongosh
{ $cos: <expression> }

Syntax Rules

  • $cos — returns the cosine of the angle in radians.
  • <expression> — a field reference, literal, or nested numeric expression.
  • Output range is always -1 to 1 (inclusive).
  • Use inside stages like $project, $addFields, or $set.
  • If the input is null, the result is null.
  • Input must be in radians, not degrees.

⚠️ Input Must Be in Radians

$cos(0)1 (0 radians = 0°)
$cos(1.571)≈ 0 (π/2 rad = 90°)
$cos(60) → wrong if you meant 60° — convert degrees first!
Formula: radians = degrees × (π / 180)

💡 $cos vs $acos

$cos — angle (radians) → cosine value (-1 to 1)
$acos — cosine value (-1 to 1) → angle (radians)
They are inverse operations: $acos($cos(x)) ≈ x within the valid domain

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (trigonometry)
Syntax{ $cos: <expression> }
Input unitRadians (any real number)
Output range-1 to 1
Common stages$project, $addFields, $set
Zero angle
{
  $cos: 0
}

Returns 1

Field
{
  $cos: "$radians"
}

Cosine of angle field

π/2
{
  $cos: 1.5707963267948966
}

Returns 0 (90°)

Null input
{
  $cos: null
}

Returns null

Examples Gallery

Compute cosines from stored radian values, convert degrees first, and explore common boundary angles with $cos.

📚 Cosine from Radians

Use an angles collection with radian measurements and compute cosine with $project.

Sample Input Documents

Suppose you have an angles collection where each document stores an angle in radians:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "radians": 0 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "radians": 1 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "radians": 2 }
]

Example 1 — Basic $cos on a Field

Compute the cosine of each stored angle:

mongosh
db.angles.aggregate([
  {
    $project: {
      radians: 1,
      cosine: { $cos: "$radians" }
    }
  }
])

How It Works

  • radians: 0cos(0) = 1
  • radians: 1cos(1) ≈ 0.5403
  • radians: 2cos(2) ≈ -0.4161

📈 Practical Patterns

Convert degrees to radians, compute x-components on the unit circle, and handle common boundary values.

Example 2 — Convert Degrees to Radians, Then $cos

When your data stores degrees, convert before applying $cos:

mongosh
db.angles.aggregate([
  {
    $project: {
      degrees: 1,
      cosine: {
        $cos: {
          $multiply: [
            "$degrees",
            { $divide: [ 3.141592653589793, 180 ] }
          ]
        }
      }
    }
  }
])

// degrees: 60  → cosine ≈ 0.5
// degrees: 90  → cosine ≈ 0
// degrees: 180 → cosine ≈ -1

How It Works

The formula is radians = degrees × (π / 180). Nest the conversion inside $cos so the pipeline handles everything in one stage.

Example 3 — x-Component on the Unit Circle

On a unit circle, the x-coordinate equals cos(θ). Compute it from a stored angle:

mongosh
db.vectors.aggregate([
  {
    $project: {
      label: 1,
      angleRadians: 1,
      xComponent: { $cos: "$angleRadians" },
      yComponent: { $sin: "$angleRadians" }
    }
  }
])

How It Works

Pair $cos with $sin to recover both coordinates from an angle. This pattern appears in robotics, game physics, and circular motion models.

Example 4 — $cos with Literal Values

Common boundary values every beginner should know:

mongosh
db.samples.aggregate([
  {
    $project: {
      cosZero:  { $cos: 0 },                    // 1
      cosPi2:   { $cos: 1.5707963267948966 },   // ≈ 0  (π/2)
      cosPi:    { $cos: 3.141592653589793 },    // ≈ -1 (π)
      cosTwoPi: { $cos: 6.283185307179586 }     // ≈ 1  (2π)
    }
  }
])

How It Works

$cos(0) = 1, $cos(π/2) = 0, and $cos(π) = -1. These edge cases help validate pipeline logic and unit tests.

🚀 Use Cases

  • Geometric calculations — compute distances, orientations, and x-components from angles.
  • Signal processing — model periodic signals and frequency analysis with cosine waves.
  • Physics and engineering — analyze oscillations, vibrations, and circular motion in stored sensor data.
  • Data visualization — generate cosine curves for charts and simulations inside aggregation pipelines.

🧠 How $cos Works

1

MongoDB reads the angle

The pipeline evaluates the input — a field like "$radians" or a numeric expression in radians.

Input
2

$cos applies the cosine function

MongoDB computes cos(angle) and returns a value between -1 and 1.

Transform
3

The result is stored in the pipeline

The cosine value is written to the field you define in $project or $addFields.

Output
=

Cosine ratio ready to use

Use in further math, pair with $sin, or feed into inverse ops like $acos.

Conclusion

The $cos operator brings standard cosine math directly into MongoDB aggregation pipelines. Remember that input angles must be in radians, and the output always falls between -1 and 1.

For geometry and physics workloads, pair $cos with $sin to recover full coordinates. Use $acos when you need the inverse — converting a cosine value back to an angle.

💡 Best Practices

✅ Do

  • Store angles in radians or convert degrees before $cos
  • Pair with $sin for full unit-circle coordinates
  • Use literal boundary tests (0, π/2, π) to validate pipelines
  • Remember output is always between -1 and 1
  • Use $acos for the inverse when recovering angles

❌ Don’t

  • Pass degree values directly to $cos without conversion
  • Confuse $cos (angle → ratio) with $acos (ratio → angle)
  • Expect exact floating-point equality — compare with tolerance
  • Forget that null input returns null
  • Mix up $cos (trig) with $cosh (hyperbolic cosine)

Key Takeaways

Knowledge Unlocked

Five things to remember about $cos

Use these points when computing cosines in MongoDB.

5
Core concepts
📝 02

{ $cos: x }

One expression.

Syntax
📏 03

Radians In

Not degrees.

Rule
🛠 04

-1 to 1

Output range.

Property
05

Not $acos

Forward vs inverse.

Important

❓ 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.
The syntax is { $cos: <expression> }. The expression can be a field reference like "$radians", a literal number, or another numeric expression.
$cos expects radians. To use degrees, convert first: multiply by Math.PI / 180 using $multiply and $divide before passing the value to $cos.
$cos takes an angle (radians) and returns a cosine value. $acos takes a cosine value (-1 to 1) and returns an angle in radians. They are inverse operations.
$cos returns null when the input is null. It does not throw an error.

Continue the Operator Series

Move on to $cosh for hyperbolic cosine, or review $convert for type conversion.

Next: $cosh →

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.

5 people found this page helpful