5

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"
icza
  • 389,944
  • 63
  • 907
  • 827
Anthony
  • 15,435
  • 4
  • 39
  • 69

1 Answers1

11

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))
icza
  • 389,944
  • 63
  • 907
  • 827
  • Is there a reason to use `hex.EncodeToString([]byte(objid))` instead of the [Hex](http://godoc.org/gopkg.in/mgo.v2/bson#ObjectId.Hex) method? –  Mar 19 '15 at 15:44
  • @BeBop I don't think so. I just didn't know about the `Hex()` method. Should I add it to the answer or you post it as a new answer? – icza Mar 19 '15 at 15:49