% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mongo.R
\name{mongo}
\alias{mongo}
\alias{mongolite}
\title{MongoDB client}
\usage{
mongo(
  collection = "test",
  db = "test",
  url = "mongodb://localhost",
  verbose = FALSE,
  options = ssl_options()
)
}
\arguments{
\item{collection}{name of collection}

\item{db}{name of database}

\item{url}{address of the mongodb server in mongo connection string
\href{https://www.mongodb.com/docs/manual/reference/connection-string}{URI format}}

\item{verbose}{emit some more output}

\item{options}{additional connection options such as SSL keys/certs.}
}
\value{
Upon success returns a pointer to a collection on the server.
The collection can be interfaced using the methods described below.
}
\description{
Connect to a MongoDB collection. Returns a \link{mongo} connection object with
methods listed below. Connections automatically get pooled between collection
and gridfs objects to the same database.
}
\details{
This manual page is deliberately minimal, see the
\href{https://jeroen.github.io/mongolite/}{mongolite user manual} for more details
and worked examples.
}
\section{Methods}{

\describe{
\item{\code{aggregate(pipeline = '{}', handler = NULL, pagesize = 1000, iterate = FALSE)}}{Execute a pipeline using the Mongo aggregation framework. Set \code{iterate = TRUE} to return an iterator instead of data frame.}
\item{\code{count(query = '{}')}}{Count the number of records matching a given \code{query}. Default counts all records in collection.}
\item{\code{disconnect(gc = TRUE)}}{Disconnect collection. The \emph{connection} gets disconnected once the client is not used by collections in the pool.}
\item{\code{distinct(key, query = '{}')}}{List unique values of a field given a particular query.}
\item{\code{drop()}}{Delete entire collection with all data and metadata.}
\item{\code{export(con = stdout(), bson = FALSE, query = '{}', fields = '{}', sort = '{"_id":1}')}}{Streams all data from collection to a \code{\link{connection}} in \href{https://ndjson.org}{jsonlines} format (similar to \href{https://www.mongodb.com/docs/database-tools/mongoexport/}{mongoexport}). Alternatively when \code{bson = TRUE} it outputs the binary \href{https://bsonspec.org/faq.html}{bson} format (similar to \href{https://www.mongodb.com/docs/database-tools/mongodump/}{mongodump}).}
\item{\code{find(query = '{}', fields = '{"_id" : 0}', sort = '{}', skip = 0, limit = 0, handler = NULL, pagesize = 1000)}}{Retrieve \code{fields} from records matching \code{query}. Default \code{handler} will return all data as a single dataframe.}
\item{\code{import(con, bson = FALSE)}}{Stream import data in \href{https://ndjson.org}{jsonlines} format from a \code{\link{connection}}, similar to the \href{https://www.mongodb.com/docs/database-tools/mongoimport/}{mongoimport} utility. Alternatively when \code{bson = TRUE} it assumes the binary \href{https://bsonspec.org/faq.html}{bson} format (similar to \href{https://www.mongodb.com/docs/database-tools/mongorestore/}{mongorestore}).}
\item{\code{index(add = NULL, remove = NULL)}}{List, add, or remove indexes from the collection. The \code{add} and \code{remove} arguments can either be a field name or json object. Returns a dataframe with current indexes.}
\item{\code{info()}}{Returns collection statistics and server info (if available).}
\item{\code{insert(data, pagesize = 1000, stop_on_error = TRUE, ...)}}{Insert rows into the collection. Argument 'data' must be a data-frame, named list (for single record) or character vector with json strings (one string for each row). For lists and data frames, arguments in \code{...} get passed to \code{\link[jsonlite:toJSON]{jsonlite::toJSON}}}
\item{\code{iterate(query = '{}', fields = '{"_id":0}', sort = '{}', skip = 0, limit = 0)}}{Runs query and returns iterator to read single records one-by-one.}
\item{\code{mapreduce(map, reduce, query = '{}', sort = '{}', limit = 0, out = NULL, scope = NULL)}}{Performs a map reduce query. The \code{map} and \code{reduce} arguments are strings containing a JavaScript function. Set \code{out} to a string to store results in a collection instead of returning.}
\item{\code{remove(query = "{}", just_one = FALSE)}}{Remove record(s) matching \code{query} from the collection.}
\item{\code{rename(name, db = NULL)}}{Change the name or database of a collection. Changing name is cheap, changing database is expensive.}
\item{\code{replace(query, update = '{}', upsert = FALSE)}}{Replace matching record(s) with value of the \code{update} argument.}
\item{\code{run(command = '{"ping": 1}', simplify = TRUE)}}{Run a raw mongodb command on the database. If the command returns data, output is simplified by default, but this can be disabled.}
\item{\code{update(query, update = '{"$set":{}}', upsert = FALSE, multiple = FALSE)}}{Modify fields of matching record(s) with value of the \code{update} argument.}
}
}

\examples{
# Connect to demo server
con <- mongo("mtcars", url =
  "mongodb+srv://readwrite:test@cluster0-84vdt.mongodb.net/test")
if(con$count() > 0) con$drop()
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()

\dontrun{
# 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://jeroen.github.io/data/diamonds.json"))
dmd$count()

# Export
dmd$drop()
}
}
\references{
\href{https://jeroen.github.io/mongolite/}{Mongolite User Manual}

Jeroen Ooms (2014). The \code{jsonlite} Package: A Practical and Consistent Mapping Between JSON Data and \R{} Objects. \emph{arXiv:1403.2805}. \url{https://arxiv.org/abs/1403.2805}
}
