英文:
Mongo Aggregate - $addFields with multiplication
问题
我正在使用官方的Golang MongoDB驱动程序,并尝试进行聚合操作。我想根据货币和薪水的乘积对条目进行排序。
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 返回 nil。
}
但是,cursor 返回了 nil。
我的 MongoDB 实体中的 "salary" 和 "currency" 都是整数类型。
英文:
I'm using the official mongo driver on golang and trying to aggregate. I want to sort entries based on the multiplication of currency and salary.
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.
}
But cursor returns nil.
My mongo entities all have "salary" and "currency" as Integer.
答案1
得分: 2
在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
操作尝试将 salary
和 currency
的 字符串 相乘。显然这不是你想要的,你想要的是将 salary
和 currency
属性的值相乘,所以在它们前面加上 $
符号:
aggregatePipeline = append(aggregatePipeline, bson.D{{
Key: "$addFields",
Value: bson.D{{
Key: "trueSalary",
Value: bson.D{{"$multiply", bson.A{"$salary", "$currency"}}},
}},
}})
英文:
In Go you should always check returned errors. That'll save you a lot of time.
cursor, err := myCollection.Aggregate(context.TODO(), aggregatePipeline)
if err != nil {
panic(err)
}
This will output something like:
> panic: (TypeMismatch) Failed to optimize pipeline :: caused by :: $multiply only supports numeric types, not string
The $multiply
operation tries to multiply the salary
and currency
strings. Obviously this is not what you want, you want to multiply the values of the salary
and currency
properties, so add a $
sign to them:
aggregatePipeline = append(aggregatePipeline, bson.D{{
Key: "$addFields",
Value: bson.D{{
Key: "trueSalary",
Value: bson.D{{"$multiply", bson.A{"$salary", "$currency"}}},
}},
}})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论