Introduction to MongoDB $acos Operator
The $acos
operator is a convenient trigonometric function operator in MongoDB that can be used to calculate the arccosine of a given angle.
Syntax
The syntax of the $acos
operator is as follows:
{ $acos: <expression> }
Here, <expression>
is a numeric expression that can be any valid numeric expression, such as a constant, a field, an expression, and so on.
Use Cases
The $acos
operator is typically used to calculate the arccosine of a given angle, that is, to calculate arccos(x). In trigonometric calculations, the $acos
operator is often used in conjunction with the $sin
and $cos
operators to calculate the sine, cosine, and arccosine of a given angle.
Example
Assume that there is a collection named planets that stores the positions and radii of celestial bodies. Each document contains the coordinates and radius information of a celestial body, as shown below:
{ "_id": 1, "name": "Earth", "radius": 6371, "position": { "x": 0.0, "y": 0.0, "z": 6371 } }
{ "_id": 2, "name": "Mars", "radius": 3389, "position": { "x": 0.0, "y": 0.0, "z": 3389 } }
Suppose we want to calculate the angular distance between Earth and Mars. We can use the following aggregation pipeline:
db.planets.aggregate([
{ $match: { name: { $in: ["Earth", "Mars"] } } },
{
$group: {
_id: null,
earth: { $first: "$$ROOT" },
mars: { $last: "$$ROOT" }
}
},
{
$project: {
angle: {
$acos: {
$cos: [
{
$subtract: [
{ $pi: 1 },
{
$divide: [
{ $multiply: ["$earth.position.x", "$mars.position.x"] },
{ $multiply: ["$earth.position.y", "$mars.position.y"] },
{ $multiply: ["$earth.position.z", "$mars.position.z"] }
]
}
]
}
]
}
}
}
}
])
In the above aggregation pipeline, the $match
operator is used to first filter out documents with names “Earth” and “Mars”, then the $group
operator is used to save them to fields named earth
and mars
, and finally the $project
operator is used to calculate the angular distance between them. In the calculation of the angular distance, we use the $cos
and $acos
operators to calculate the cosine and arccosine of a given angle, respectively.
Conclusion
The $acos
operator is a convenient trigonometric function operator in MongoDB that can be used to calculate the arccosine of a given angle. In practical applications, the $acos
operator is often used in conjunction with the $sin
and $cos
operators to calculate the sine, cosine, and arccosine of a given angle.