python - 在 golang 中使用 mgo 排序为接口(interface)数组的字符串数组

标签 python mongodb python-3.x go mgo

这是我的代码:

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 似乎是一个接口(interface)数组:

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

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

60FPS

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

var results []CatMixing

我有 _id 但没有 comb , comb 显示为空

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

我已经使用 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)

关于python - 在 golang 中使用 mgo 排序为接口(interface)数组的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43826463/

相关文章:

linux - 群晖NAS服务器上的mongoctl

python - 有没有办法使用伪随机序列或哈希函数模拟队列的 python random.shuffle?

python - 一旦玩家达到 Python 游戏的设定时间,如何停止程序

python - 将键值对添加到基于另一个列表 Python 的字典列表中

python - 对于 argparse,子解析器本质上是相互排斥的吗?

python - 密码验证器: password needs to contain EXACTLY one spacial character?

python - 如何移动 matplotlib 图中的一条线?

python - 重复 RSA 加密/解密有时会失败,并出现明文太大错误

Mongodb 聚合数组中的子文档

python - 将 Python 3.1 与 TextMate 一起使用