I am working with MongoDB in my Go application, and pull some data out and store it in a bson.M (which . Here is an example, of getting the bson.M object from the DB and then printing it (let's call this object data
):
[map[_id:ObjectID("XXXXXXX") address:XX decimal:18 providers:map[currency:value] symbol:LINK]
Which looks correct to me.
I think want to loop over the map in the providers
field (as you can see, it's a map in there as well). I've done a few attempts, but each time I am blocked.
Due to what I've read in the docs here and the testing I've done, it looks like a bson.M and primitive.M are the same, and they are each treated as a map[string]interface{}
.
When I attempted to assert it to a map[string]string
I go a panic error:
// code run
data["providers"].(map[string]string)
//error received
panic: interface conversion: interface {} is primitive.M, not map[string]string
The reason for this, is I want to loop over the providers
field, and when I try to loop as-is, I get this error:
// code to run
for key, provider := range data["providers"] {...}
// error received
cannot range over data["providers"] (map index expression of type interface{})
I have read that I might need to do something with marshaling and decoding, but I feel like I'm just missing a step as to why I would need to do those, or how they would help.
In any case to summarize:
How does one loop over a primitive.M/bson.M/map[string]interface{}?
How does one convert a primitive.M/bson.M/map[string]interface{} to a map[string]string?
It looks like I might be trying to do the opposite of this entry, and it looks like this entry is giving me conflicting information. Hoping to edit the question as I understand more what my real problem is. Thank you!