mongo's go driver returns a bson timestamp as https://godoc.org/go.mongodb.org/mongo-driver/bson/primitive#Timestamp is there a way to convert it to time.Time
mongo's go driver returns a bson timestamp as https://godoc.org/go.mongodb.org/mongo-driver/bson/primitive#Timestamp is there a way to convert it to time.Time
https://docs.mongodb.com/manual/reference/bson-types/#timestamps
As you can see in mongodb official website, BSON Timestamps contains two values, 'T' for the seconds since Unix epoch and 'I' for an incrementing ordinal for operations within a given second.
So if you want to convert the bson timestamp to time.Time, you may just use time.Unix(timestamp.T, 0)
Similarly to convert current time.Time to primitive.Timestamp type, we can use
primitive.Timestamp{T: uint32(time.Now().Unix()), I: 0}
Using primitive.Timestamp in mongo object modeling results in Timestamp(1639732596, 0) datatype in mongo collection. And when encoded to json, it results in object like :
{ "T": 1639732596, "I": 0 }
In most of the use cases, it would be sufficient enough to use time.Time type for object model. This will result in ISODate("2021-12-17T09:14:33.608Z") datatype in mongo collection. And when encoded to json, results in string like :
"2021-12-17T09:14:33.608Z"