Get ObjectIdHex value from mgo request
I'm still a newbie, and when I see multiple questions on SO, it looks like this, I can't reproduce the output that some OP was asking for ( this answer looks like the closest ).
I'm doing something quite simple, I end up in a collection users
in mongo and all I want to do is return the value _id
as a string. I'm going to eventually push these _id
towards 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 it gives out:
ObjectIdHex("537f700b537461b70c5f0000")
ObjectIdHex("537f700b537461b70c600000")
ObjectIdHex("537f700b537461b70c610000")
ObjectIdHex("537f700b537461b70c620000")
I went through the bson # m docs and thought I was using the map correctly to increase the value. So I think my request results in:
{"_id" : ObjectIdHex("Some_ID") }
but if ObjectIdHex ("ID") is a value, how easy is it to get the string inside.
Ideal way out:
"537f700b537461b70c5f0000"
"537f700b537461b70c600000"
"537f700b537461b70c610000"
"537f700b537461b70c620000"
source to share
The value associated with the key "_id"
is of a type bson.ObjectId
that is simply equal string
.
bson.M
is a type map[string]interface{}
, so you need to Enter assertion to get the id as ObjectId
:
objid, ok := m["_id"].(ObjectId)
if !ok {
panic("Not ObjectId")
}
And it ObjectId
has a method ObjectId.Hex()
that returns exactly what you want: the object id as a "pure" hex string:
fmt.Println(objid.Hex())
Alternatives
objid
can be simply converted to string
because its base type string
. Thus, you can use a number of additional parameters to convert it to hexadecimal string
:
hexid := fmt.Sprintf("%x", string(objid))
If you just want to print it, you can do it directly:
fmt.Printf("%x", string(objid))
Note. ... Converting it to string
is important, otherwise the package fmt
is called by its method String()
, which results in a type string ObjectIdHex("537f700b537461b70c5f0000")
, which is what would be converted to hex, which is clearly not what you want.
Alternatively, you can use encoding/hex
and hex.EncodeToString()
:
hexid := hex.EncodeToString([]byte(objid))
source to share