Mongo 聚合 - $addFields 乘法

Mongo Aggregate - $addFields with multiplication

我在 golang 上使用官方 mongo 驱动程序并尝试聚合。我想根据货币和薪水的乘积对条目进行排序。

import (
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)


func main () {
    //...
    aggregatePipeline := bson.A{}
    aggregatePipeline = append(aggregatePipeline, bson.D{{Key: "$addFields", Value: bson.D{{Key: "trueSalary", Value: bson.D{{"$multiply", bson.A{"salary", "currency"}}}}}}})
    aggregatePipeline = append(aggregatePipeline, bson.D{{"$sort", bson.D{{"trueSalary", -1}}}})
    cursor , _ := myCollection.Aggregate(context.TODO(), aggregatePipeline)
   // cursor returns nil.
}

但是游标returns nil.

我的 mongo 实体的“薪水”和“货币”均为整数。

在 Go 中你应该总是检查返回的错误。这将为您节省很多时间。

cursor, err := myCollection.Aggregate(context.TODO(), aggregatePipeline)
if err != nil {
    panic(err)
}

这将输出如下内容:

panic: (TypeMismatch) Failed to optimize pipeline :: caused by :: $multiply only supports numeric types, not string

$multiply 操作试图乘以 salarycurrency 字符串 。显然这不是你想要的,你想要乘以 salarycurrency 属性的值,所以给它们添加一个 $ 符号:

aggregatePipeline = append(aggregatePipeline, bson.D{{
    Key: "$addFields",
    Value: bson.D{{
        Key:   "trueSalary",
        Value: bson.D{{"$multiply", bson.A{"$salary", "$currency"}}},
    }},
}})