jeroen / mongolite

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

Date in nested list doesn't recognized as a date #223

Open lisette-bouwmeester1 opened 3 years ago

lisette-bouwmeester1 commented 3 years ago

Hi,

I try to add data as a nested list. This also includes a date variable. However this isn't recognized as a date, which means that I can't use $find based on date. Please find my code below:

my_list <- list(
  list(
    var1 = "string1",
    var2 = "string2",
    recorded_at =  strftime(as.POSIXlt("2021-01-01 12:00:00 CEST", "UTC") , "%Y-%m-%dT%H:%M:%S%z"),
    var3 = 70,

    map1 = list(
      left = list(
        x = 10,
        y = 100,
        z = 110
      ),      

      right = list(
        x = 20,
        y = 200,
        z = 220
      ),      

      total = list(
        x = 30,
        y = 300,
        z = 330
      )
    )
  )
)

my_df <- fromJSON(toJSON(my_list, auto_unbox = T)) # convert the nested lists to a dataframe
db$insert(my_df)

I tried to attach the type of it in the list as well: recorded_at ='{"$date": "2021-01-01T12:00:00Z"}' but this also doesn't work.

Finally I found that it is possible to add recorded_at with $update

tm <- strftime(as.POSIXlt("2021-01-01 12:00:00 CEST", "UTC") , "%Y-%m-%dT%H:%M:%S%z")
db$update('{"var1": "string1"}', 
          paste0('{"$set": {"recorded_at": { "$date" :"', tm, '"}}}'))

This works, but I was wondering whether there is a possibility to already include date formats in the nested list. Or maybe someone has a much easier solution. Thanks!

jonekeat commented 8 months ago

@jeroen I also facing this issue, may I know is there any way we can specify valid mongodb data type in JSON?