Golang mgo create objectid from a hexadecimal string example

May 19, 2016

Storing a string that holds the hexadecimal string of a objectID is done by using the bson package with function 'objectIdHex()'.


Let's say you have a string that represents the hexadecimal value of the id like this one:


If you want to insert it to a field in a document you should do the following.

bsonObjectID := bson.ObjectIdHex("573ce4451e02f4bae78788aa")

collection.Insert(bson.M{"fieldThatContainsTheId" : bsonObjectID})