Hi, I am working with MongoDB with Go Driver v2, but I’ve encountered a strange problem. When I insert one record to the database, I use primitve.NewObjectID()
to assign a new ID, but it becomes Binary.createFromBase64('<HEX Value>', 0)
.
My Model:
type Event struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Title string
}
My insert snippet:
event := model.Event{
ID: primitive.NewObjectID(),
Title: "New Event",
}
if _, err := client.Database(<DB_NAME>).Collection("events").InsertOne(ctx, event); err != nil {
panic(err)
}
When I print out the event model in Golang, it shows ObjectID, which is correct:
fmt.Printf("Data Type: %T, Data Value: %v", event.ID, event.ID)
Data Type: primitive.ObjectID, Data Value: ObjectID("67b06afea7becf9aeca2c397")
But when I retrive data in database, it shows otherwise:
db.events.findOne({})
{
_id: Binary.createFromBase64('Z7Bp/imGeLj5GWHk', 0),
title: 'New Event',
}
Also, when I retrive this data by findOne({})
with Golang, it could successfully decode to ObjectId, but it’s weird that it was stored in binary in the DB. If I don’t specify the ID field, the DB will generate a new ObjectID for me, which is ObjectID not binary. So I thought there might be some problems.
Does anyone also encounter this problem? How do you solve it?
Versions:
go - 1.24
go driver - v2.0.0
mongodb version - v8.0.4