R - Read & Write files from MongoDB with security

 

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

If a special character is present in the username or password (e.g. '%', '@', ...). The conversion table is available here : http://www.w3schools.com/tags/ref_urlencode.asp

user

password

ip

port : default port is 27017

authentificationDatabase : The authentification database is sometimes different from the database where the collections are

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://", user, ":", password, "@", ip, ":", port, "/", authentificationDatabase)

# 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}}')

 

Â