Mikhail Mikhail - 1 year ago 171
R Question

Inserting json object into MongoDB using mongolite R package

There are quite a few packages for dealing with MongoDB in R. I started using 'mongolite' package, because I work with 'jsonlite' and 'mongolite' builds on top of 'jsonlite'. However, I'm a bit puzzled, why insert function in 'mongolite' does not allow to insert json objects (help says it inserts dataframes)?

What package should I use to store json objects and do simple queries?

Answer Source

If you use jsonlite you can still use mongolite to insert your data, but only if it can also be coerced to a data.frame (using fromJSON). For example:

js <- '[
    "id": 1,
    "val": "a"
    "id": 2,
    "val": "b"
    "id": 3,
    "val": "c"
] '


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

# Complete! Processed total of 3 rows.
# [1] TRUE

However, my understanding is that the mongolite package will only insert data.frames. For example, taking a more complicated JSON structure you'll see we can't insert it using mongolite

js <- '{"foo":[{"id":1,"val":"a"},{"id":2,"val":"b"},{"id":3,"val":"c"}],"bar":[[{"id":1,"val":"a"},{"id":2,"val":"b"},{"id":3,"val":"c"}]]}'

## if we try to insert this using mongolite we get an error
## because it is not a data.frame
> mongo$insert(fromJSON(js))
Error: is.data.frame(data) is not TRUE

To insert a more complicated JSON structure we can use the mongo.bson.from.json function from the rmongodb package

mongo <- mongo.create()
# [1] TRUE

db <- "test"
coll <- "test"

bs <- mongo.bson.from.JSON(js)

mongo.insert(mongo, ns = paste0(db ,".", coll), b = bs)
# [1] TRUE

Taking note that mongodb actually stores BSON:

MongoDB represents JSON documents in binary-encoded format called BSON behind the scenes. BSON extends the JSON model to provide additional data types and to be efficient for encoding and decoding within different languages

Reference: JSON and BSON

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download