When working with the MongoDB driver from go.mongodb.org/mongo-driver, converting a primitive.ObjectID to a string can be challenging.
Attempting to type assert a mongo-driver.ObjectID to a string using mongoDoc["_id"].(string) results in a runtime panic:
panic: interface conversion: interface {} is primitive.ObjectID, not string
The error occurs because mongoDoc["_id"] holds an interface value of type interface{} with a concrete value of primitive.ObjectID. To successfully convert to a string, we need to type assert the primitive.ObjectID value itself instead of the interface value.
mongoId := mongoDoc["_id"].(primitive.ObjectID) stringObjectID := mongoId.Hex()
The Hex() method on the primitive.ObjectID type provides a hexadecimal representation of its bytes.
The above is the detailed content of How to Convert a `primitive.ObjectID` to a String in Go with the MongoDB Driver?. For more information, please follow other related articles on the PHP Chinese website!