我遇到了一个问题,想要从我的mongodb数据库中减go 2个字段,然后以变量的形式返回它们.

我正在使用bson.我将在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相关问答推荐

MongoDB聚合匹配字符串字符

如何在MongoDB中使用Aggregation来计算两个键相同但字段不同的对象数组的总值,并将其合并为一个?

MongoDB获取所有文档谁的S子文档只包含一个特定值?

Mongo查找条件:不存在

如何将交易列表变成 token 数量的对象?

使用 AngularJs 和 MongoDB/Mongoose

使用 MongoDb 处理迁移

加载时将 mongo 存储的日期转换回自 Unix 纪元以来的毫秒数?

pymongo 排序和 find_one 问题

MongoDB插入引发重复键错误

$lookup 结果 mongodb 的计数

具有多个字段的mongodb文本搜索

为什么不建议在 MongoDB 中使用服务器端存储函数?

如何使用 mongodb 和 php 正确处理分页查询?

如何使用 c# 2.0 驱动程序将数据插入到 mongodb 集合中?

MongoDB $or 查询

Golang + MongoDB 嵌入类型(将一个 struct 嵌入到另一个 struct 中)

mongodb nodejs - 转换圆形 struct

$orderby 和 Sort 之间的 MongoDB 区别

Mongoose / MongoDB 用户通知方案建议