dongwen1909 2018-04-03 05:21 采纳率: 0%
浏览 250
已采纳

如何使用golang在mongodb中对具有相同user_id的收集数据进行$ group?

I'm trying to make the sum of the price of the product which having same user_id using golang. But I don't know how I will get this. I tried $group in the following code

Struct for product

type Product struct {
  Id         int     `json:"id" bson:"_id"`
  Name       string  `json:"name" bson:"name"`
  Sku        string  `json:"sku" bson:"sku"`
  Category   string  `json:"category" bson:"category"`
  Stock      int     `json:"stock" bson:"stock"`
  Price      float64 `json:"price" bson:"price"`
  Sale_price float64 `json:"sale_price" bson:"sale_price"`
  UpdatedOn  int64   `json:"updated_on" bson:"updated_on"`
  UserId     int     `json:"user_id" bson:"user_id"`
}

Struct for the customer

type Customer struct {
  Id               int    `json:"id" bson:"_id"`
  FirstName        string `json:"first_name" bson:"first_name"`
  LastName         string `json:"last_name" bson:"last_name"`
  Email            string `json:"email" bson:"email"`
  PhoneNumber      string `json:"phone_number" bson:"phone_number"`
}

function from where the data will retrieve

func GetProducts(c *gin.Context) {
    mongoSession := config.ConnectDb()                                         //connection to database
    collection := mongoSession.DB(config.Database).C(config.ProductCollection) //session
    pipeline := []bson.M{
        bson.M{"$group": bson.M{"user_id": 1}}, bson.M{"$sum": bson.M{"price": "price"}},
    } //query i tried
    fmt.Println(pipeline)
    pipe := collection.Pipe(pipeline)
    resp := []bson.M{}
    err = pipe.All(&resp)
    if err != nil {
        fmt.Println("Errored: %#v 
", err)
    }
    fmt.Println(resp)
    GetResponseList(c, response)
}

The data viewed in the image-

In the above image the user_id of the product is same. I want to group this data and calculate the price.

I also read the documentation of the Mongodb this one but don't understand how to do in golang can anyone explain it in simple way how to make the query for this. Thanks

  • 写回答

1条回答 默认 最新

  • douxing6434 2018-04-03 07:11
    关注

    When grouping using $group, you have to use the special _id property to tell what you want to group by.

    And when referring to existing properties / fields, you have to use the $ sign in front of their names, e.g. $user_id.

    And besides the _id you may list additional properties whose value may be some aggregate value (like $sum).

    This is how your pipeline may look like:

    pipeline := []bson.M{
        {
            "$group": bson.M{
                "_id":       "$user_id",
                "sum_price": bson.M{"$sum": "$price"},
            },
        },
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵