jeroen / mongolite

Fast and Simple MongoDB Client for R
https://jeroen.github.io/mongolite/
287 stars 65 forks source link

ObjectId - timestamp converter #212

Closed fmmattioni closed 3 years ago

fmmattioni commented 3 years ago

Is it possible to convert the ObjectId to a timestamp with mongolite?

Reference here: https://docs.mongodb.com/manual/reference/method/ObjectId.getTimestamp/

jeroen commented 3 years ago

@fmmattioni the first 4 bytes of the oid contain the timestamp. You can convert easily convert it in R, for example:

oid_to_timestamp <- function(oid){
  val <- strtoi(paste0('0x', substring(oid, 1, 8)))
  structure(val, class = c("POSIXct", "POSIXt"))
}

oid_to_timestamp('5349b4ddd2781d08c09890f3')
# [1] "2014-04-12 23:49:17 CEST"
fmmattioni commented 3 years ago

@jeroen that is fantastic!!! Thank you!!!