Golang Driver, how to map to a document to a struct if document fields can have multiple types

I am totally new to MongoDB and i am trying to map the planet example data to golang structs with the original MongoDb golang driver and i would greatly appreciate the help.

I ran into a problem as i was trying to map the temperature data, which exists in the database as int32, double and null, to a golang struct.

To be specific, the planet temperature data is a sub document and has 3 fields, min, mean and max. Each field can exist in some documents as int, in some as double and in some as null. Google was no help so after that i asked ChatGPT a series of questions, the best solution was:

  1. use an Interface as the data type in the struct so that it can hold different data types
  2. use “Find” instead of “FindOne”, because i want to get multiple documents
  3. use the “Cursor” with “Next” to loop over the documents
  4. use type assertion with switch to get to the correct type and cast the data

i did not get it to work yet, but is that the best way to deal with that kind of Situation?
Any help, pointers or suggestions are most welcome.
Thank you

Hey @Marcus_Bonhagen1 welcome to the forum and thanks for the question! The Go BSON library allows unmarshaling BSON “int32” and “double” types into a Go float64. If you also need to support BSON “null”, you can use a *float64, which will be set to nil for BSON “null”.

To unmarshal documents like the ones from the sample_guides.planets dataset into a Go struct, use a struct like this:

type surfaceTemperatureC struct {
	Min  *float64
	Max  *float64
	Mean *float64

Check out an example on the Go Playground here.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.