Accessing MongoDB from Go: Custom Data Marshalling and Unmarshalling
In accessing MongoDB with Go, you may encounter scenarios where the data stored in the database differs in type from what you have defined in your Go structs. For instance, your MongoDB date field may be stored as a string, while your Go struct expects a time.Time value.
To address this, Go provides the ability to implement custom data marshalling and unmarshalling logic. By customizing this logic, you can perform type conversions or apply specific formatting during data exchange between MongoDB and your Go structs.
One way to implement custom logic is by defining your own types that implement the bson.Getter and bson.Setter interfaces. These interfaces allow you to control the marshalling and unmarshalling process. For instance, you can extend your clientConfigData type with an additional field of type time.Time named EndDate:
type clientConfigData struct { SMTPAssoc int `bson:"smtp_assoc"` PlanType string `bson:"plan_type"` EndDateStr string `bson:"end_date"` EndDate time.Time `bson:"-"` }
The bson:"-" tag indicates that the EndDate field should not be persisted in MongoDB.
Next, implement the GetBSON and SetBSON methods to handle custom marshalling and unmarshalling:
func (c *clientConfigData) SetBSON(raw bson.Raw) (err error) { type my clientConfigData if err = raw.Unmarshal((*my)(c)); err != nil { return } c.EndDate, err = time.Parse(endDateLayout, c.EndDateStr) return } func (c *clientConfigData) GetBSON() (interface{}, error) { c.EndDateStr = c.EndDate.Format(endDateLayout) type my *clientConfigData return my(c), nil }
In SetBSON(), the raw data is unmarshalled into the custom type my. Subsequently, the EndDateStr field is parsed into a time.Time value and assigned to EndDate.
In GetBSON(), the EndDateStr field is populated from EndDate, and then the custom type my is returned. This indicates that the data is ready to be marshalled and persisted to MongoDB.
By implementing this custom marshalling and unmarshalling logic, you can bridge the type discrepancy between MongoDB and your Go structs, allowing you to seamlessly manipulate data between the two platforms.
The above is the detailed content of How to Handle Type Discrepancies When Accessing MongoDB from Go?. For more information, please follow other related articles on the PHP Chinese website!