Inserting json date obeject in mongodb from R

℡╲_俬逩灬. 提交于 2019-12-06 16:21:59

You can use library(mongolite) to insert dates correctly for you. However, I've only managed to get it to correctly insert dates using data.frames. It fails to insert dates correctly using lists or JSON strings.

Here is a working example using a data.frame to insert the data.

library(mongolite)

m <- mongo(collection = "test_dates", db = "test", url = "mongodb://localhost")

# m$drop()

df <- data.frame(id = c("site1","site2"),
                 ts = c(Sys.time(), Sys.time()))

m$insert(df)
#Complete! Processed total of 2 rows.
#$nInserted
#[1] 2
#
#$nMatched
#[1] 0
#
#$nRemoved
#[1] 0
#
#$nUpserted
#[1] 0
#
#$writeErrors
#list()

A potential (but less than ideal) solution could be to coerce your list to a data.frame and then insert that.

rev<-data.frame(ts=c("2017-01-06 05:30:00","2017-01-06 05:31:00","2017-

01-06 05:32:00","2017-01-06 05:33:00","2017-01-06 05:34:00"),value=c(10,20,30,40,50))
rev$ts<-as.POSIXct(strptime(rev$ts,format = "%Y-%m-%d %H:%M:%S",tz=""))

revno<-"Revision1"

mylist <- list()
mylist[[ revno ]] <- rev
mylist["lastRevision"]<-revno

m$insert(data.frame(mylist)) 

Or alternatively, insert your list, and then write a function to convert ts values to ISODates() directly within mongo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!