MongoDB error: Insert date into MongoDB in ISO format through JSON file

2.2k Views Asked by At

I have tried to load date field into MongoDB via JSON file but I'm getting error as write erros:

{BulkWriteError{index=0,code-52,message='The doller($) prefixed field '$date' in 'ExpirationDate.$date' is not a valid for storage.'

Tried below methods, none of them are worked:

"ExpirartionDate":{
  "$date":"2020-07-07"
}

"ExpirartionDate":ISODate("2020-0-07")

"ExpirartionDate":{ISODate("2020-0-07")}

Please advise correct format to insert date as ISO date in MongoDB via JSON file.

1

There are 1 best solutions below

5
MarcRo On

From the official documentation:

For dates between years 1970 and 9999, inclusive:

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

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

For dates before year 1970 or after year 9999:

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

Where the values are as follows:

"<millis>"
   - A 64-bit signed integer as string. The value represents milliseconds relative to the epoch.

"<ISO-8601 Date/Time Format>"
   - A date in [ISO-8601 Internet Date/Time Format](https://datatracker.ietf.org/doc/html/rfc3339#section-5.6) as string.

   - The date/time has a maximum time precision of milliseconds:
      - Fractional seconds have exactly 3 decimal places if the fractional part is non-zero.
      - Otherwise, fractional seconds SHOULD be omitted if zero.

The 'time' portion of an ISO 8601 date is optional. So your first attempt will work, I just confirmed this.

Your json should looks like this:

[
  {
    "ExpirationDate": { "$date": "2020-07-07" }
  }
]