In go I am storing a structure with an interface{} field to be able to store different sub structures in the mongodb record. When I read back the record into the struct I can see the interface{} field has type primitive.D.
Hi Matthew,
Not exactly sure what the problem here, but other than interface you can also use either bson.D (ordered), or bson.M (unordered). For example:
type Record struct {
Type string
SubStruct bson.D
}
And you can just call Cursor.Decode() instead of the marshal/unmarshal, for example:
cursor, err := collection.Find(context.TODO(), bson.D{})
if err != nil {
log.Fatal(err)
}
defer cursor.Close(context.TODO())
for cursor.Next(context.Background()) {
doc := &Record{}
err = cursor.Decode(doc)
if err != nil {
log.Fatal(err)
}
fmt.Println(doc)
}
The above is assuming you’re using the current version of MongoDB Go driver v1.0.3. If you have further question, please include the driver version that you’re using.
Regards,
Wan.