在 golang 中使用 mgo 排序为接口数组的字符串数组

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

这是我的代码:

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))

        }

    }


}

问题是 comb 似乎是一个接口数组 :

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

但在 mongo 中它显示为字符串数组:

所以我的映射不起作用... 如果我尝试:

var results []CatMixing

我有 _id 但没有梳子,梳子显示为空

我不明白为什么它不是字符串数组以及为什么我的映射不起作用。

我已经使用 python 向 mongodb 添加了数据:

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)

所以我不明白为什么 comb 不是字符串数组以及如何获取它...

感谢和问候

首先,您可以使用 []CatMixing 更改查询中的 results 变量。因为 .All(result interface{}) 需要一个 interace{} 参数并不意味着你不能传递你的结构。

请注意,Go 中的 interface{} 可以包含任何类型,包括您的结构。

试试这个代码:

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