How to send multiple documents using RMongo

2019-07-23 17:39发布

I am following the conventions from http://docs.mongodb.org/manual/reference/method/db.collection.insert/
to send a batch of multiple documents in one call of RMongo::dbInsertDocument.

data=data.frame(A=c(1,2),B=c(3,4))  
L=lapply(split(data,rownames(data)),as.list)  
names(L)=NULL  
dataJSON = toJSON(L)  
cat(dataJSON)  

which gives the following result:

[  
 {  
  "A":1,
  "B":3
 },
 {
  "A":2,
  "B":4
 }
]

Then

dbInsertDocument(rmongo.object=myRmongo.object, collection=myCollection, doc=dataJSON)

returns the following error:

Error in ls(envir = envir, all.names = private) :  
invalid 'envir' argument

Note that if I replace

L = L[[1]

Then

cat(dataJSON)  

gives the following result:

{  
 "A":1,
 "B":3
}

and the same call to dbInsertDocument works with no error (and the data is indeed sent to the database)

1条回答
迷人小祖宗
2楼-- · 2019-07-23 18:02

Has anyone figured this out? I would really like a better way to do this, but for now am just looping over the list (not ideal)

data=data.frame(A=c(1,2),B=c(3,4))  
L=lapply(split(data,rownames(data)),as.list)  
names(L)=NULL  
for (i in 1:NROW(L)) {
    dataJSON = toJSON(L[[i]])  
    output <- dbInsertDocument(mongo, "test_data7", dataJSON)
}
查看更多
登录 后发表回答