R - Read & Write files from MongoDB

 

Github project : https://github.com/saagie/example-R-read-and-write-from-mongodb

Official documentation

This example is based on the mongolite R package. The github for this package with other exemples is available at this address : https://github.com/jeroenooms/mongolite, and the CRAN page with full documentation is here : https://cran.r-project.org/web/packages/mongolite/mongolite.pdf.

Dependencies

R package

mongolite : https://cran.r-project.org/web/packages/mongolite/index.html

Used to interact with MongoDB.

Linux package

libssl-dev & libsasl2-dev

Dependency for the mongolite package.

Parameters

ip

port : default port is 27017

database : Database where the collections are

collection : Can be a new collection to create it

data : data to write to MongoDB

Code explaination

Connection

# Build the connection uri from the parameters above
uri <- paste0("mongodb://", ip, ":", port, "/")

# Connect to the database
con <- mongo(collection = collection, db = database, url = uri)

Count

# Count the number of documents in the collection
con$count()

Insert

# Insert new data in the collection
con$insert(data)

Find

# Read data from the collection
con$find()

Find with mongo query

# Read data from any valid mongo query
con$find('{"cyl" : 6, "mpg" : { "$gt" : 20}}')