$cos (aggregation) 在本页面

    $cos

    4.2版中的新功能。

    返回以弧度为单位的值的余弦值。

    $cos 具有以下语法:

    1. { $cos: <expression> }

    $cos接受可解析为数字的任何有效表达式。如果表达式返回以度为单位的值,请使用$degreesToRadians运算符将结果转换为弧度。

    默认情况下以形式$cos返回值是double$cos$cos还可以以128-bit小数的形式返回值,只要<expression>解析为一个128-bit的十进制值。

    有关表达式的更多信息,请参见 表达式。

    行为

    nullNaN+/- Infinity

    如果参数解析的值为null或指向缺少的字段,则$cos返回null。如果参数解析为NaN,则$cos返回NaN。如果参数解析为负无穷大或正无穷大, $cos则会引发错误。

    例子 结果
    { $cos: NaN } NaN
    { $cos: null } null
    { $cos : Infinity}
    or
    { $cos : -Infinity }
    引发类似于以下格式化输出的错误消息:
    “errmsg” : “Failed to optimize pipeline :: caused by :: cannot apply $cos to -inf, value must in (-inf,inf)”

    例子

    度数的余弦值

    trigonometry集合包含一个文档,该文档存储斜边和直角三角形中的一个角度:

    1. {
    2. "_id" : ObjectId("5c50782193f833234ba90d85"),
    3. "angle_a" : NumberDecimal("53.13010235415597870314438744090659"),
    4. "hypotenuse" : NumberDecimal("5")
    5. }

    以下聚合操作使用该 $cos表达式来计算相邻的边,angle_a并使用$addFields管道阶段将其添加到输入文档中 。

    1. db.trigonometry.aggregate([
    2. {
    3. $addFields : {
    4. "side_a" : {
    5. $multiply : [
    6. { $cos : {$degreesToRadians : "$angle_a"} },
    7. "$hypotenuse"
    8. ]
    9. }
    10. }
    11. }
    12. ])

    $degreesToRadians表达式将的度数值转换为angle_a以弧度为单位的等效值。

    该操作返回以下结果:

    1. {
    2. "_id" : ObjectId("5c50782193f833234ba90d85"),
    3. "angle_a" : NumberDecimal("53.13010235415597870314438744090659"),
    4. "side_a" : NumberDecimal("2.999999999999999999999999999999999"),
    5. "hypotenuse" : NumberDecimal("5"),
    6. }

    由于angle_ahypotenuse被存储为 128-bit小数,因此输出 $cos为128-bit小数。

    弧度中的正弦值

    trigonometry集合包含一个文档,该文档存储斜边和直角三角形中的一个角度:

    1. {
    2. "_id" : ObjectId("5c50782193f833234ba90d85"),
    3. "angle_a" : NumberDecimal("0.9272952180016122324285124629224288"),
    4. "hypotenuse" : NumberDecimal("5")
    5. }

    以下聚合操作使用该 $cos表达式来计算相邻的边,angle_a并使用$addFields管道阶段将其添加到输入文档中 。

    1. db.trigonometry.aggregate([
    2. {
    3. $addFields : {
    4. "side_b" : {
    5. $multiply : [
    6. { $cos : "$angle_a" },
    7. "$hypotenuse"
    8. ]
    9. }
    10. }
    11. }
    12. ])

    该命令返回以下输出:

    1. {
    2. "_id" : ObjectId("5c50782193f833234ba90d85"),
    3. "angle_a" : NumberDecimal("0.9272952180016122324285124629224288"),
    4. "side_b" : NumberDecimal("3.000000000000000000000000000000000"),
    5. "hypotenuse" : NumberDecimal("5"),
    6. }

    由于angle_ahypotenuse被存储为 128-bit小数,因此输出 $cos为128-bit小数。

    译者:李冠飞

    校对: