@Meinrad_Hermanek thanks for posting and welcome!
The implementation you posted has two issues:
- The string that looks like
{"$date": ... }is actually the Extended JSON representation for a BSON “UTC datetime” field, not the BSON representation. By default, a Gotime.Timeis marshaled to a BSON “UTC datetime” field, but the currentMarshalBSONfunction is actually returning a nested document with a single field called$date. - Implementations of the bson.Marshaler interface (i.e. the
MarshalBSONfunction) must return an entire BSON document. However, what you want to do is override the encoding for a field, not create a nested document. To encode an individual field in a BSON document, you actually want to implement the bson.ValueMarshaler interface instead.
To resolve those two issues, replace MarshalBSON with MarshalBSONValue and return the default BSON field encoding for a Go time.Time value:
func (v FcsDate) MarshalBSONValue() (bsontype.Type, []byte, error) {
return bson.MarshalValue(time.Time(v))
}
See an example on the Go Playground here.