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
A MongoDB ObjectId is a 12-byte UUID can be used as a HEX string representation with 24 chars in length.
The 12-byte ObjectId consists of: A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch. A 5-byte random value generated once per process. This random value is unique to the machine and process.
An ObjectID is a unique, not null integer field used to uniquely identify rows in tables in a geodatabase. ObjectIDs are limited to 32-bit values, which store a maximum value of 2,147,483,647.
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()
nowadays you can just do mongoId.Hex()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With