用 Golang 减去 mongodb 中的两个字段
Substract two fields in mongodb with Golang
我 运行 想从我的 mongodb 数据库中减去 2 个字段并 return 将它们放在一个变量中。
我正在使用 bson.M 在 golang 中执行操作,但没有成功。
col2 := db.Collection("products")
pipe2 := []bson.M{
{"$group": bson.M{
"_id": IDUser,
"total": bson.M{"$subtract": {"$actualPrice", "$oldPrice"}},
}},
}
cur2, err := col2.Aggregate(ctx, pipe2)
$subtract
运算符需要一个数组(在 Go 中可能是一个切片)。
要向输出文档添加字段,请使用 $addFields
阶段:
pipe2 := []bson.M{
{"$addFields": bson.M{
"total": bson.M{"$subtract": []string{"$actualPrice", "$oldPrice"}},
}},
}
正在使用以下文件对其进行测试:
{ "_id" : "u1", "actualPrice" : 100, "oldPrice" : 80 }
{ "_id" : "u2", "actualPrice" : 200, "oldPrice" : 190 }
测试代码:
cur2, err := col2.Aggregate(ctx, pipe2)
if err != nil {
panic(err)
}
var results []bson.M
if err = cur2.All(ctx, &results); err != nil {
panic(err)
}
fmt.Println(results)
输出:
[map[_id:u1 actualPrice:100 oldPrice:80 total:20]
map[_id:u2 actualPrice:200 oldPrice:190 total:10]]
我 运行 想从我的 mongodb 数据库中减去 2 个字段并 return 将它们放在一个变量中。
我正在使用 bson.M 在 golang 中执行操作,但没有成功。
col2 := db.Collection("products")
pipe2 := []bson.M{
{"$group": bson.M{
"_id": IDUser,
"total": bson.M{"$subtract": {"$actualPrice", "$oldPrice"}},
}},
}
cur2, err := col2.Aggregate(ctx, pipe2)
$subtract
运算符需要一个数组(在 Go 中可能是一个切片)。
要向输出文档添加字段,请使用 $addFields
阶段:
pipe2 := []bson.M{
{"$addFields": bson.M{
"total": bson.M{"$subtract": []string{"$actualPrice", "$oldPrice"}},
}},
}
正在使用以下文件对其进行测试:
{ "_id" : "u1", "actualPrice" : 100, "oldPrice" : 80 }
{ "_id" : "u2", "actualPrice" : 200, "oldPrice" : 190 }
测试代码:
cur2, err := col2.Aggregate(ctx, pipe2)
if err != nil {
panic(err)
}
var results []bson.M
if err = cur2.All(ctx, &results); err != nil {
panic(err)
}
fmt.Println(results)
输出:
[map[_id:u1 actualPrice:100 oldPrice:80 total:20]
map[_id:u2 actualPrice:200 oldPrice:190 total:10]]