@Meinrad_Hermanek thanks for posting and welcome!

The implementation you posted has two issues:

  1. 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 Go time.Time is marshaled to a BSON “UTC datetime” field, but the current MarshalBSON function is actually returning a nested document with a single field called $date.
  2. Implementations of the bson.Marshaler interface (i.e. the MarshalBSON function) 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.

1 Like