Ezio123
Ezio123

Reputation: 376

How to insert a dataframe to mongodb using rmongodb

I have following dataframe

enter image description here

how can I insert it to mongoDB using rmongodb?

Upvotes: 2

Views: 2048

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

You need to create a list of JSON objects, each of which will be inserted into the Mongo DB:

library(rjson)
df <- data.frame(rowLabels=c("Birrarung Marr", "Bourke Street Mall (North)", "Bourke Street Mall (South)", "Flagstaff Station", "Flinders St Station Underpass", "Melbourne Central", "Princes Bridge", "Sandridge Bridge", "State Library", "Town Hall (West)"),
                 locationMax = c(8592, 3213, 3127, 138, 4472, 3923, 4595, 1758, 4252, 2926))
df_list <- lapply(split(df, 1:nrow(df)), function(x) mongo.bson.from.JSON(toJSON(x)))

mongo <- mongo.create()                                # connect to Mongo on localhost
if (mongo.is.connected(mongo) == TRUE) {
    icoll <- paste(db, "test", sep=".")
    mongo.insert.batch(mongo, icoll, df_list)          # insert into the MongoDB
    dbs <- mongo.get.database.collections(mongo, db)
    print(dbs)
    mongo.find.all(mongo, icoll)
}

Upvotes: 2

Related Questions