Search code examples
mongodbgomgo

How to $group the collection data having same user_id in mongodb using golang?


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 \n", 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


Solution

  • 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"},
            },
        },
    }