Search code examples
goobjectidmongo-go

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


Solution

  • 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.