Context
I’m using MongoDB to store data where one of the fields can be of any type, ranging from primitive types (such as int
, string
, etc.) to more complex structures (like map
, slice
, or even combinations of these). As a result, my Go struct contains a field with the type any
to accommodate this flexibility.
Problem
When I retrieve this data from MongoDB, the Go MongoDB driver converts the field into a primitive.D
type, which is essentially a slice of primitive.E
structs (each containing Key
and Value
properties). This transformation causes an issue when the data is marshaled to JSON: the result ends up being formatted like this (where bars[i].value
is the field in question):
{
"id": "123",
"bars": [
{
"name": "map",
"value": [
{
"Key": "im",
"Value": "a map"
}
]
}
]
}
Example
I’ve created a minimal example to reproduce the issue: Link to Gist
Questions
I have a few questions regarding this behavior:
-
Why does this happen?
Why does the MongoDB driver convert this field into aprimitive.D
type instead of a more straightforward representation likemap[string]interface{}
? -
What was the reasoning behind this decision?
Why did the MongoDB Go driver choose to represent this data asprimitive.D
instead of something more directly usable in Go, like amap
orslice
? -
Is there a way to control the type conversion?
I know I can manually convert theprimitive.D
into a map when marshalling to JSON, but is there a way to instruct the driver to convert it into a map (or another suitable structure) directly during the retrieval process?