Obtain ObjectIdHex value from mgo query

余生颓废 提交于 2019-12-10 15:18:30

问题


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.M
err = 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"

回答1:


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

Alternatives

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


来源:https://stackoverflow.com/questions/29146922/obtain-objectidhex-value-from-mgo-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!