Search code examples
mongodbgomongo-driver

Cannot parse BSON datetime from string


I'm parsing BSON from strings using the mongo driver library.

AFAIK, the following should be valid BSON:

{
  "createdAt": {"$date": "2024-01-01T00:00:00.000Z"}
}

but the following test code

var v bson.M
bsonString = `{"createdAt": {"$date": "2024-01-01T00:00:00.000Z"}}`
err := bson.UnmarshalExtJSON([]byte(bsonString), true, &v)
if err != nil {
    t.Fatalf("cannot unmarshal: %v", err)
}

fails with error

cannot unmarshal: error decoding key createdAt: invalid JSON input; expected {

Why?


Solution

  • In bson.UnmarshalExtJSON, set canonicalOnly to false since Canonical-mode requires dates to be represented as quoted numbers (strings), being milliseconds relative to the epoch.

    From the Extended JSON v2 reference:

    Canonical: {"$date": {"$numberLong": "<millis>"}}

    Relaxed: {"$date": "<ISO-8601 Date/Time Format>"}

    And

    Where the values are as follows:

    • "<millis>"

      • A 64-bit signed integer as string. The value represents milliseconds relative to the epoch.

    So presumably negative numbers for "before 1970".

    Go Playground example, output with canonicalOnly=false:

    {"createdAt":{"$date":{"$numberLong":"1704067200000"}}}