I'm switching to the new mongo go driver (mongo-go-driver), away from mgo
One of our functions is no longer working despite the decoding method not changing (into a map[string]interface{})
I believe that what is happening is that the returned data is not being handled correctly as a map[string]interface{}
The data ingested is a mongo aggregate query:
result = map[query_key:procedure_on_cities query_type:run procedure query_value:map[aggregate:[map[£match:map[Source:Cities]] map[£sort:map[Order:1]]] collection:aggregate_stats db:stats] _id:ObjectID("5c5410fac2a7b1b1beae52bc")]
What we need to do is replace the £ with $ in the aggregation for it to run correctly (we encode $ as £ initially to not run into issues with the $ being interpreted incorrectly when the query is put together on the frontend
Previously with mgo, we simply did this:
if returnedQuery, ok := result["query_value"].(map[string]interface{}); ok {
queryToRun = replace£With$(returnedQuery)
}
But this is no longer working...
So the bit that we are wanting to handle as a map[string]interface to pass into the function is this:
query_value:map[aggregate:[map[£match:map[Source:Cities]] map[£sort:map[Order:1]]] map[£sort:map[Order:1]]] collection:aggregate_stats db:stats]
We assumed, like with mgo, we could just do the previously mentioned type assertion
In my testing, I isolate the part with the £ that I want to replace:
result2 = result["query_value"].(map[string]interface{})
Then I want to check to see the datatypes and whether what's in the aggregate is even a map[string]interface{}
for key, value := range result2 {
fmt.Println("key from result2:", key, " || ", "value from result 2:", value)
if key == "aggregate" {
fmt.Println("FOUND AGGREGATE || ", "value:", value, " || type: ", reflect.TypeOf(value))
}
if valueMSI, ok := value.([]interface{}); ok {
fmt.Println("Please, print this", keyMSI)
}
}
But this doesn't print the last statement. WHY?! This is what result2 is:
result2 = map[aggregate:[map[£match:map[Source:Cities]] map[£sort:map[Order:1]]] collection:aggregate_stats db:stats]
It is a []interface{} isn't it?! It should be printing that statement since the aggregate key's associated value is an array that contains maps
When performing type checks the response was:
primitive.A
Is primitive.A not treated as an []interface{}?
The issue here is that the new mongo driver uses a primitive.A datatype for []interface{}
primitive.A has the underlying datatype of []interface{} but the type literal is primitive.A
To solve the problem you need first do the type assertion for primitive.A then do a conversion to the type literal[]interface{}:
I've imported the package for bson primitive with a name:
import (
bsonNewGoDriverPrimitive "go.mongodb.org/mongo-driver/bson/primitive"
)
if valuePA, ok := value.(bsonNewGoDriverPrimitive.A); ok {
vI := []interface{}(valuePA)}