Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Primitive.ObjectID

I am using mongo-driver from go.mongodb.org/mongo-driver. I already converted primitive.ObjectID to string Using this link Primitive.ObjectID to string

Now i need to convert string to primitive.ObjectID

like image 611
Faizal Ahamed Avatar asked May 09 '26 20:05

Faizal Ahamed


1 Answers

The linked answer uses ObjectID.Hex() to obtain a string of the hexadecimal representation of the ObjectID.

The very same API docs have a ObjectIDFromHex function to do the reverse:

func ObjectIDFromHex(s string) (ObjectID, error)

Use it as follows:

objID, err := primitive.ObjectIDFromHex(hexString)
if err != nil {
  panic(err)
}

Quick reminder: always read the docs of the libraries you are using.

like image 86
Marc Avatar answered May 11 '26 15:05

Marc