Search code examples
pythonmongodbpython-3.xgomgo

array of strings sorting as array of Interfaces with mgo in golang


here is my code :

type CatMixing struct {
    Id      bson.ObjectId `json:"id" bson:"_id,omitempty"`
    CatMix []string  `json:"comb"`
}

func main(){
    session, err := mgo.Dial("127.0.0.1")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    c := session.DB("MixiIng").C("Combination")
    var results []bson.M
    err5 := c.Find(nil).Limit(10).All(&results)
    if err5 == nil {

    }
        fmt.Println(results)
    for _,catm := range results {
        fmt.Println(catm)
        for _,catm2 := range catm {
            fmt.Println(reflect.TypeOf(catm2))

        }

    }


}

the problem is that it seems that comb is an array of interfaces :

map[_id:ObjectIdHex("590e5cb36aace327da180c89") comb:[60fps]]
bson.ObjectId
[]interface {}

but in mongo it shows as an array of string :

60FPS

So my mapping is not working ... If i try with :

var results []CatMixing

i have the _id but not comb , comb appears as empty

I don't understand why it's not an array of string and why my mapping is not working.

I've added data to mongodb with python :

from pymongo import MongoClient
client = MongoClient()
db = client['MixiIng']
collection = db['Combination']
combination = {}
result = [["60fps"]]
for r in result :
    combination = {"comb":r}
    collection.insert_one(combination)

So i don't understand why comb is not an array of string and how to get it...

thanks and regards


Solution

  • First you can change the results variable from the query using your []CatMixing. Because .All(result interface{}) needs an interace{} argument doesn't mean you can't pass your struct.

    Note that interface{} in Go can hold any type including your struct.

    try this code :

    var results [] CatMixing
    err := c.Find(bson.M{}).Limit(10).All(&results)
    if err != nil {
       fmt.Fatal(err)
    }
    fmt.Println(results)