Search code examples
stringmongodbgoobjectidmongo-go

Primitive.ObjectID to string in Golang


I am trying to convert type primitive.ObjectID to string type in Go. I am using mongo-driver from go.mongodb.org/mongo-driver.

I tried using type assertion like-

mongoId := mongoDoc["_id"];
stringObjectID := mongoId.(string)

Which VSCode accepts. Code gets compiled and when it reaches this specific line of code, it throws this error

panic: interface conversion: interface {} is primitive.ObjectID, not string

Solution

  • The error message tells mongoDoc["_id"] is of type interface{} which holds a value of type primitive.ObjectID. This is not a string, it's a distinct type. You can only type assert primitive.ObjectID from the interface value.

    If you want a string representation of this MongoDB ObjectId, you may use its ObjectID.Hex() method to get the hex representation of the ObjectId's bytes:

    mongoId := mongoDoc["_id"]
    stringObjectID := mongoId.(primitive.ObjectID).Hex()