6

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

DAme
  • 697
  • 8
  • 21
Faizal Ahamed
  • 118
  • 1
  • 4
  • 7

1 Answers1

20

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.

Marc
  • 19,394
  • 6
  • 47
  • 51