r - rmongodb batch insert error: Expected a list of mongo.bson class objects

旧时模样 提交于 2019-12-11 23:46:45

问题


Situation

I have a list of athletes lst_ath

lst_ath <- structure(list(`1` = structure(c("1125266", "ath_1"), .Names = c("id", 
"name")), `2` = structure(c("1125265", "ath_2"), .Names = c("id", 
"name")), `3` = structure(c("1125264", "ath_3"), .Names = c("id", 
"name")), `4` = structure(c("1125263", "ath_4"), .Names = c("id", 
"name")), `5` = structure(c("1125262", "ath_5"), .Names = c("id", 
"name")), `6` = structure(c("1125261", "ath_6"), .Names = c("id", 
"name")), `7` = structure(c("1125260", "ath_7"), .Names = c("id", 
"name")), `8` = structure(c("1125259", "ath_8"), .Names = c("id", 
"name")), `9` = structure(c("1125258", "ath_9"), .Names = c("id", 
"name")), `10` = structure(c("1125257", "ath_10", "(NZ)"), .Names = c("id", 
"name", "country"))), .Names = c("1", "2", "3", "4", "5", "6", 
"7", "8", "9", "10"))

And a connection to a local mongodb called "athletes", with a collection called "athletes"

> library(rmongodb)
> mongo <- mongo.create()
> 
> #check connection
> mongo.is.connected(mongo)
[1] TRUE
> 
> #set the database
> db <- "athletes"
> mongo.get.database.collections(mongo, db)
[1] "athletes.athletes"

And a mongo.bson object query from the list lst_ath

query <- mongo.bson.from.list(lst_ath)
str(query)
Class 'mongo.bson'  atomic [1:1] 0
  ..- attr(*, "mongo.bson")=<externalptr> 
>

Issue

I'm trying to batch insert the query object using mongo.insert.batch(mongo, db, query), but get an error:

> mongo.insert.batch(mongo, db, query)
Error in mongo.insert.batch(mongo, db, query) : 
  Expected a list of mongo.bson class objects

As I created query with mongo.bson.from.list(lst_ath), and my str(query) shows Class 'mongo.bson' atomic [1:1] 0 I can't figure out the error.

What am I missing?

Update

As well as @NicE 's solution, I also need to define the collection that is being inserted into, not just the database, i.e:

> #set the database
> db <- "athletes.athletes"

回答1:


Looks like you are making an array when you call mongo.bson.from.list on you list of vectors. Since mongo.insert.batch needs query to be a list of 'mongo.bson' it gives you an error.

Try this:

#make a mongo bson for each element of lst_ath
query <- lapply(lst_ath,function(x){mongo.bson.from.list(as.list(x))})


#check that query is a list of mongo.bson objects
str(query)
#List of 10
# $ 1 :Class 'mongo.bson'  atomic [1:1] 0
#  .. ..- attr(*, "mongo.bson")=<externalptr> 
# $ 2 :Class 'mongo.bson'  atomic [1:1] 0
#  .. ..- attr(*, "mongo.bson")=<externalptr> 
# $ 3 :Class 'mongo.bson'  atomic [1:1] 0
#  .. ..- attr(*, "mongo.bson")=<externalptr> 


#insert them
mongo.insert.batch(mongo, db, query)


来源:https://stackoverflow.com/questions/28603804/r-rmongodb-batch-insert-error-expected-a-list-of-mongo-bson-class-objects

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