Timeseries date support for millisecond format

Can the time field in the timeseries collection be in milliseconds versus an ISODATE?

Hi :wave: @Allan_Chase,

Welcome to the MongoDB Community Forums :sparkles:

The timeField is a required field, that references the name of the field for the date in each document and it has to be of BSON type Date. It is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970).

test> var mydate1 = new Date()
test> mydate1
ISODate("2023-04-10T06:59:40.755Z")

test> var mydate2 = ISODate()
test> mydate2
ISODate("2023-04-10T06:59:53.231Z")

For example, if you try to insert the timestamp with the ISODate, it will get inserted into the ts collection and will return an acknowledged true:

ts> db.sensor.insert({_id:  ObjectId("642e640ebba9b652048e9be3"), timestamp: new Date()})
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("642e640ebba9b652048e9be3") }
}

However, if you try to insert the data after converting it into a millisecond, it will throw an error:

ts> db.sensor.insert({_id:  ObjectId("642e640ebba9b652048e9be3"), timestamp: new Date().getTime()})
Uncaught:
MongoBulkWriteError: 'timestamp' must be present and contain a valid BSON UTC datetime value
Result: BulkWriteResult {
  insertedCount: 1,
  matchedCount: 0,
  modifiedCount: 0,
  deletedCount: 0,
  upsertedCount: 0,
  upsertedIds: {},
  insertedIds: { '0': ObjectId("642e640ebba9b652048e9be3") }
}
Write Errors: [
  WriteError {
    err: {
      index: 0,
      code: 2,
      errmsg: "'timestamp' must be present and contain a valid BSON UTC datetime value",
      errInfo: undefined,
      op: {
        _id: ObjectId("642e640ebba9b652048e9be3"),
        timestamp: 1681110368277
      }
    }
  }
]

To work around this you can convert it into a millisecond for your use case at the application level, like as follows:

test> timestamp.getTime();
1681110368277

I hope it helps. Let us know if you have any further queries.

Best,
Kushagra

Thank you Kushagra, that was a perfect example and explanation. I might, however, think about duplicating the column and create one to please the timeseries requirements and keep our original ts (so really they would be the same thing, different format).

1 Like

Hi :wave: @Allan_Chase,

Thanks for your kind words. Yes, that could be a workaround of creating an additional field in the ts collection to store the timestamp in milliseconds apart from the default timeField field.

~ Kushagra

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.