$cos (Cosine)
Last updated: 2026-10-09
$cos (Cosine)
$cos returns the cosine of a value expressed in radians. It is used for vector projection, waveform analysis, and rotation math. A null or missing argument yields null, NaN input returns NaN, and ±Infinity throws an error. The cosine range is -1 to 1, and $acos provides the inverse function. Convert between degrees and radians with $degreesToRadians and $radiansToDegrees rather than hand-multiplying by pi.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $cos: <numeric-expression> }
⚙️ Parameters
| radians | A numeric expression in radians. |
|---|
Returns:The cosine of the input radians; null when null or missing, error for ±Infinity
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $cos: cosine after converting degrees to radians
db.trig.aggregate([
{ $project: {
x: { $cos: { $degreesToRadians: '$deg' } }
} }
])
Output:
{ '_id': 1, 'x': 0.5 }
{ '_id': 2, 'x': 0.8660254037844387 }
📌 Notes
- The input is in radians; convert angles first
- The range is between -1 and 1
- With $sin it decomposes coordinates, and their squares always sum to 1
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat unit does $cos expect?
ARadians; convert angles with $degreesToRadians first.
QWhat is the range of $cos results?
AResults fall between -1 and 1.
QHow are $cos and $sin related?
AFor the same angle, the squares of $cos and $sin sum to 1, so they can be converted into each other.