2018-04-03 05:21
浏览 247

如何使用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
    pipe := collection.Pipe(pipeline)
    resp := []bson.M{}
    err = pipe.All(&resp)
    if err != nil {
        fmt.Println("Errored: %#v 
", err)
    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条回答 默认 最新

相关推荐 更多相似问题