Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive.ObjectID to string in Golang

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
like image 554
Rabi Avatar asked Mar 26 '20 10:03

Rabi


People also ask

Is MongoDB ObjectID a string?

A MongoDB ObjectId is a 12-byte UUID can be used as a HEX string representation with 24 chars in length.

How many bytes is ObjectID?

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.

What is ObjectID?

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.


2 Answers

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()
like image 92
icza Avatar answered Oct 12 '22 14:10

icza


nowadays you can just do mongoId.Hex()

like image 33
bashizip Avatar answered Oct 12 '22 14:10

bashizip