MongoDB and R

Using an MongoDB server together with R

Write data to database

# Connection settings
library(mongolite)

USER = "me"
PASS = "myfancypw"
HOST = "myHost.com"
DBCON = 'admin'
  
db='myDb'
collection = "MyCollection"

How to work with a connection object

# Make connection
URI = sprintf("mongodb://%s:%s@%s/%s", USER, PASS, HOST, DBCON)
c <- mongo(collection = collection, db = db,  url = URI)

# insert data.frame into Collection
c$insert(d)

# create index for field
c$index(add = '{"depth" : 1}')

# create index for field id in Collection with name Samples with unique property
cmd = 'db.Samples.createIndex({"id": 1}, { unique: true })'
c$run(cmd)


# read in all data from database
alldata <- c$find('{}')