Home >Backend Development >Golang >How do I convert a primitive.ObjectID to a string in Go using the mongo-driver?
Converting Primitive.ObjectID to String in Go with Mongo-Driver
When working with MongoDB in Go using the mongo-driver, developers may encounter the need to convert a primitive.ObjectID to a string. However, attempting to cast a primitive.ObjectID directly to a string using type assertion can result in the error:
panic: interface conversion: interface {} is primitive.ObjectID, not string
This is because primitive.ObjectID is a distinct type, and interface{} cannot be directly type asserted to primitive.ObjectID. To convert a primitive.ObjectID to a string representation, the ObjectID.Hex() method can be utilized. Here's an example:
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // Connect to MongoDB client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { panic(err) } defer client.Disconnect(context.Background()) // Get the ObjectId from a MongoDB document mongoDoc := bson.D{{"_id", primitive.NewObjectID()}} // Convert ObjectId to string using ObjectID.Hex() stringObjectID := mongoDoc["_id"].(primitive.ObjectID).Hex() fmt.Println(stringObjectID) // Output: 03174bcc88dea692233713e1 }
The above is the detailed content of How do I convert a primitive.ObjectID to a string in Go using the mongo-driver?. For more information, please follow other related articles on the PHP Chinese website!