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.
About the R package:
- Book: Mongolite User Manual
- Presentation: UseR 2015 slides
Example using a public test server
# Connect to mongolabs
con <- mongo("mtcars", url = "mongodb://readwrite:[email protected]:43942/jeroen_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()
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
On OS-X sasl is included with the system so only openssl is needed.
brew install openssl