Hi
We have to import several different JSON Exports into MonogDB using Go. What we do is fetching the JSON from a database, unmarshalling it into a struct and save the struct into a Mongo collection. This works. The problem I struggle is the handling of the dates. The dates are stored in the format “YYYY-MM-DDTHH:MM:SS” in the incoming JSON. When using the normal unmarshal function it claims with a parsing time error “parsing time \"\\\"2023-01-10T08:56:02\\\"\" as \"\\\"2006-01-02T15:04:05Z07:00\\\"\": cannot parse \"\\\"\" as \"Z07:00\"
”.
For this reason, I created then an own type
type MyDate time.time
and a implmented the UnmarshalJSON interface.
func (v *MyDate) UnmarshalJSON(b []byte) error {
parsedTime, err := time.Parse("\"2006-01-02T15:04:05\"", string(b))
if err != nil {
return err
}
*v = MyDate(parsedTime)
return nil
}
So far so good, I got my date in my Go struct
type MyData struct {
FieldS string
FieldI int64
FieldD *MyDate
}
When I now try to save this struct to MongoDB, it creates an empty Object for MyDate. Therefore I implmented the MarshalBSON interface:
func (v FcsDate) MarshalBSON() ([]byte, error) {
return bson.Marshal(map[string]map[string]interface{}{
"$date": {"$numberLong": fmt.Sprintf("%v", time.Time(v).UnixMilli())},
})
}
This works, and my date is stored in the collection, but as it seems, it’s not really a date. When checking with Compass, it’s shown as an object, when checking with Atlas it’s shown as a date. When trying to project it using an aggregation pipeline it claims with “can’t convert from BSON type object to Date”. When I look into another collection from another running application holding a date, then the JSON representation is the same {$date:{$numberLong: nnn}}
What am I doing wrong? I could use string instead of a date, and then everything works technically fine, but my date is still not a date, it’s a string. What solution would you suggest to solve this issue?