4 / 4
Mar 2

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

I just had the same issue and found the answer. I couldn’t find it anywhere in the documentation or migration guide.

If you look at the go.mod you’ll probably see two mongo-drivers, one is 1.17.2 and the other is 2.0.0.

The import path for primitive.ObjectID is “/mongo-driver/bson/primitive” which looks like it’s using the 1.17.2 version.

I switched over to using bson.ObjectID and bson.ObjectIDFromHex() because it uses the “/mongo-driver/v2/bson” import path.

I simply didn’t provide a ID when initializing the struct since I have the bson:"_id,omitempty" tag on the ID field of the struct.

It created correctly and I was able to provide the hex as a string, then parse using the method mentioned above.

Odd that I wasn’t listed under “What’s New” section of the driver documentation. I feel like this should be added to the “Breaking Changes” seeing that most people are still using primitive.

Find a Document - Go Driver v2.0 If you follow this link to findOne documentation, it’s still using primitive so I don’t know if my fix is correct and the documentation is lagging the release of V2 or what.

Thanks for noting this, @Steven_Johnson. You are correct, the bson/primitive package has been merged into the bson package. This will be added to the “breaking changes” section in the “What’s New in 2.0” page, and the rest of the documentation will be updated to reflect this as well.

8 days later