String to Primitive.ObjectID

16.5k Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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.