dselivanov / rmongodb

R driver for MongoDB
53 stars 26 forks source link

convenience function to write data.frames #36

Closed stanstrup closed 10 years ago

stanstrup commented 10 years ago

Hi. I started playing around with mongo today. As this was all new to me I was quite annoyed that there was no easy way to write a data.frame to the database as far as I could find.

To make it easier I made the function below and I though I would post it here in case you found it an interesting addition.

It converts a data.frame to a list of mongo.bson's that can be fed to mongo.insert.batch directly. The original data.frame can be re-produced with mongo.find.all.

dataframe2bson=function(dataframe){

# Put each row to a seperate list item
data_list = apply(dataframe,1,as.list)

# Convert any numbers saved as string to numeric adata
data_list = lapply(data_list,function(x) {    lapply(x,function(y) {
                                                                      if (suppressWarnings(!is.na(as.numeric(y)))) {as.numeric(y)}else{y}
                                                    })
                  })

# Iterate over the table and create the BSON object 
bson_data = lapply(data_list,function(x){
                                          idx=1
                                          names = names(x)
                                          buf <- mongo.bson.buffer.create()

                                          lapply(x,function(y) {
                                                                  mongo.bson.buffer.append(buf, names[idx], y)
                                                                  idx<<- idx+1
                                                })

                                          mongo.bson.from.buffer(buf)
                   })

return(bson_data)
}
stanstrup commented 10 years ago

Available in https://github.com/stanstrup/rmongodb.quick.

schmidb commented 10 years ago