Skip to content

jeroen/mongolite

Repository files navigation

mongolite

Fast and Simple MongoDB Client for R

CRAN_Status_Badge CRAN RStudio mirror downloads Research software impact

High-level, high-performance MongoDB client based on libmongoc and jsonlite. Includes support for aggregation, indexing, map-reduce, streaming, SSL encryption and SASL authentication. The vignette gives a brief overview of the available methods in the package.

Documentation

About the R package:

Hello World

Example using a public test server

con <- mongo("mtcars", url =
  "mongodb+srv://readwrite:test@cluster0-84vdt.mongodb.net/test")

# Wipe collection
if(con$count() > 0) 
  con$drop()
  
# Insert some data
con$insert(mtcars)
stopifnot(con$count() == nrow(mtcars))

# Query data
mydata <- con$find()
stopifnot(all.equal(mydata, mtcars))
con$drop()

# Automatically disconnect when connection is removed
rm(con)
gc()

Insert/retrieve data from your local mongodb server:

# Init connection to local mongod
library(mongolite)
m <- mongo(collection = "diamonds")

# Insert test data
data(diamonds, package="ggplot2")
m$insert(diamonds)

# Check records
m$count()
nrow(diamonds)

# Perform a query and retrieve data
out <- m$find('{"cut" : "Premium", "price" : { "$lt" : 1000 } }')

# Compare
nrow(out)
nrow(subset(diamonds, cut == "Premium" & price < 1000))

More advanced features include map reduce:

# Cross-table
tbl <- m$mapreduce(
  map = "function(){emit({cut:this.cut, color:this.color}, 1)}",
  reduce = "function(id, counts){return Array.sum(counts)}"
)
# Same as:
data.frame(with(diamonds, table(cut, color)))

Importing and exporting json or bson data:

# Stream jsonlines into a connection
tmp <- tempfile()
m$export(file(tmp))

# Stream it back in R
library(jsonlite)
mydata <- stream_in(file(tmp))

# Or into mongo
m2 <- mongo("diamonds2")
m2$count()
m2$import(file(tmp))
m2$count()

# Remove the collection
m$drop()
m2$drop()

Installation

Binary packages for OS-X or Windows can be installed directly from CRAN:

install.packages("mongolite")

Installation from source on Linux requires openssl and Cyrus SASL (not GNU sasl). On Debian or Ubuntu use libssl-dev and libsasl2-dev:

sudo apt-get install -y libssl-dev libsasl2-dev

On Fedora, CentOS or RHEL use openssl-devel and cyrus-sasl-devel:

sudo yum install openssl-devel cyrus-sasl-devel

About

Fast and Simple MongoDB Client for R

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages