本文介绍了从mgo查询中获取ObjectIdHex值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我还是新手,虽然我看到类似这样的多个问题,但我无法再现一些OP所要求的输出(这个答案看起来最接近)。 我正在做一件相当简单的事情,我在mongo打了一个 p> objid,ok:= m [_ id]。(ObjectId) if!ok { panic (Not ObjectId)} ObjectId 有一个 ObjectId.Hex() 方法,对象id作为纯十六进制字符串: fmt.Println(objid.Hex()) 替代品 objid 可以简单地转换为 string ,因为它的基础类型是 string 。因此,您可以使用其他选项将其转换为十六进制 string : hexid:= fmt.Sprintf(%x,string(objid)) 如果你只是想打印它,你可以直接做: fmt.Printf(%x,string(objid) ) 注意:将其转换为 string 很重要,否则 fmt 包会调用它的 String()方法,这会产生一个字符串例如 ObjectIdHex(537f700b537461b70c5f0000),这就是转换为十六进制,这显然不是你想要的。 或者,您可以使用 encoding / hex 包和 hex .EncodeToString() 函数: hexid: = hex.EncodeToString([] byte(objid)) I'm still new to go and while I see multiple questions on SO similar to this, I'm unable to reproduce the output some OP's had requested (this answer looking the closest). I'm doing something fairly simple, I'm hitting a users collection in mongo and all I want to do is get the _id value back as a string. I'm going to eventually push these _id's up to NSQ but that's the brunt of my task.var users []bson.Merr = sess.DB("db_name").C("users").Find(bson.M{}).All(&users)if err != nil { os.Exit(1)}for _, user := range users { fmt.Printf("%+v \n", user["_id"])}Today this outputs:ObjectIdHex("537f700b537461b70c5f0000")ObjectIdHex("537f700b537461b70c600000")ObjectIdHex("537f700b537461b70c610000")ObjectIdHex("537f700b537461b70c620000")I went through the bson#m docs and thought I was correctly using the map in order to extra the value. So I think, my query results in:{"_id" : ObjectIdHex("Some_ID") }but if ObjectIdHex("ID") is the value, how do I simply get the string within there. So ideal output:"537f700b537461b70c5f0000""537f700b537461b70c600000""537f700b537461b70c610000""537f700b537461b70c620000" 解决方案 The value associated with key "_id" is of type bson.ObjectId which is simply a string.bson.M is a type map[string]interface{}, so you need Type assertion to get the id as an ObjectId:objid, ok := m["_id"].(ObjectId)if !ok { panic("Not ObjectId")}And the ObjectId has a ObjectId.Hex() method which returns exactly what you want: the object id as a "pure" hex string:fmt.Println(objid.Hex())Alternativesobjid can simply be converted to string because its underlying type is string. So you can use a number of further options to convert it to a hex string:hexid := fmt.Sprintf("%x", string(objid))If you just want to print it, you can do directly:fmt.Printf("%x", string(objid))Note: Converting it to string is important else the fmt package would call its String() method which results in a string like ObjectIdHex("537f700b537461b70c5f0000") and this is what would be converted to hex which is clearly not what you want.Alternatively you can use the encoding/hex package and the hex.EncodeToString() function:hexid := hex.EncodeToString([]byte(objid)) 这篇关于从mgo查询中获取ObjectIdHex值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-03 09:18