jeroen / mongolite

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

numeric NA in R is converted to string NA in mongo #179

Closed deann88 closed 5 years ago

deann88 commented 5 years ago

I have observed this behaviour which seems pretty strange to me.

If we have a NA value in R which belongs to a numeric format, I would expect it not to appear in mongo at all or be null, however, in mongo it changes type and becomes a string with value "NA".

myCollection$insert(
 list(
  a=as.double(NA) %>% jsonlite::unbox(), #same issue even if we do not unbox
  b=as.integer(NA) %>% jsonlite::unbox(), #same issue even if we do not unbox
  c = as.character(NA) %>% jsonlite::unbox() 
 )
)

Versions. jsonlite - 1.5 mongolite - 2.0

jeroen commented 5 years ago

This is unfortunately by design, because the JSON format does not natively support NA values. So we need to convert them either to null or to a string. You can control this with the na argument:

m <- mongolite::mongo('testtypes')
mydata <- list(a = NA_real_, b = NA_integer_, c = NA_character_)
m$insert(mydata, na = 'null', auto_unbox = TRUE)
m$insert(mydata, na = 'string', auto_unbox = TRUE)
m$export()
m$drop()