Learn R Programming

mongolite (version 0.5)

mongo: MongoDB client

Description

Connect to a MongoDB collection.

Usage

mongo(collection = "test", db = "test", url = "mongodb://localhost",
  verbose = TRUE)

Arguments

collection
name of collection
db
name of database
url
address of the mongodb server in mongo connection string http://docs.mongodb.org/manual/reference/connection-string/{URI format}.
verbose
emit some more output

Value

  • Upon success returns a pointer to a collection on the server. The collection can be interfaced using the methods described below.

emph

arXiv:1403.2805

url

http://arxiv.org/abs/1403.2805

References

Jeroen Ooms (2014). The jsonlite Package: A Practical and Consistent Mapping Between JSON Data and R

Examples

Run this code
# dplyr example
library(nycflights13)

# Insert some data
m <- mongo(collection = "nycflights")
m$drop()
m$insert(flights)

# Basic queries
m$count('{"month":1, "day":1}')
jan1 <- m$find('{"month":1, "day":1}')

# Sorting
jan1 <- m$find('{"month":1,"day":1}', sort='{"distance":-1}')
head(jan1)

# Sorting on large data requires index
m$index(add = "distance")
allflights <- m$find(sort='{"distance":-1}')

# Select columns
jan1 <- m$find('{"month":1,"day":1}', fields = '{"_id":0, "distance":1, "carrier":1}')

# List unique values
m$distinct("carrier")
m$distinct("carrier", '{"distance":{"$gt":3000}}')

# Tabulate
m$aggregate('[{"$group":{"_id":"$carrier", "count": {"$sum":1}, "average":{"$avg":"$distance"}}}]')

# Map-reduce (binning)
hist <- m$mapreduce(
  map = "function(){emit(Math.floor(this.distance/100)*100, 1)}",
  reduce = "function(id, counts){return Array.sum(counts)}"
)

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

# Remove the collection
m$drop()

# Import from jsonlines stream from connection
dmd <- mongo("diamonds")
dmd$import(url("http://jeroenooms.github.io/data/diamonds.json))
dmd$count()

# Export
dmd$drop()

Run the code above in your browser using DataLab