R MongoDB Database Connection

MongoDB is a NoSQL (Not only SQL) open-source document-oriented database management system. This is suitable for modern internet applications. It provides dynamic queries, scalability, secondary indexes, fast atomic updates, and we can easily use more than one database in a project.

To interact MongoDB with R, we need to install packages for mongo. The mongolite package is very fast and simple MongoDB client for R. Let's first install this package.


install.packages("mongolite")

Start local MongoDB Server

Please refer the MongoDB Tutorial in details for MongoDB installation and start up processes.





MongoDB Create Collection

Before writing the mongodb connection code, first include the mongolite package. R provides mongo() function to connect to mongoDB server, it returns a mongo connection object. The syntax of create mongo connection is as follows -

mongo(collection = "test", db = "test", url = "mongodb://localhost", options = ssl_options())

Here, the collection is the name of the collection, dbname is the name of the database, url is the address of mongodb server and options are the additional connection options. The following code connects to the students collection.

library('mongolite')
mongo <- mongo("students" , url = "mongodb://127.0.0.1:27017/school")

MongoDB Insert data

To insert data in MongoDB collection, use mongo$insert() method. It has the given syntax -

insert(data, pagesize = 1000, stop_on_error = TRUE, ...)

Here, the argument 'data' must be a data-frame, named list (for single record) or character vector with json strings (one string for each row). The following code inserts data frame in a mongodb collection.

> df <- data.frame(id = c(1:4), name = c("Mary", "Soy", "Alexa", "Roxy"), class = 5)
> mongo$insert(df)
List of 5
 $ nInserted  : num 4
 $ nMatched   : num 0
 $ nRemoved   : num 0
 $ nUpserted  : num 0
 $ writeErrors: list()
> 




MongoDB Find data

The mongo$find() method fetches the data from collection. Here is the syntax -

find(query = '{}', fields = '{"_id" : 0}', sort = '{}', skip = 0, limit = 0, handler = NULL, pagesize)

It retrieve fields from records matching query. By default, the handler will return all data as a single dataframe.

mongo$find()
mongo$find('{"cyl" : 6, "mpg" : { "$gt" : 20}}')


MongoDB Update data

It modify fields of matching record(s) with value of the update argument. The mongo$update() method updates the data in a collection. Here is the syntax-

update(query, update = '{"$set":{}}', upsert = FALSE, multiple = FALSE)
mongoID <- "5755f646ceeb7846c87afd90"
## to add a single value to an array
mongo$update(query = paste0('{"_id": { "$oid" : "', mongoID, '" } }'),
	 update = '{ "$addToSet" : { "value_array" :  "checkedByR"  } }')


MongoDB Remove Data

We can use the remove() method to remove record(s) matching query from the collection.

remove(query = "{}", just_one = FALSE)


MongoDB Count data

The mongo.count() method counts the number of documents in a collection. Default counts all records in collection.

# Count the number of documents in the collection
mongo$count()




MongoDB Iterate Data

R provides iterate() method that runs the query and returns iterator to read single records one-by-one. Here is the syntax -

iterate(query = '{}', fields = '{"_id":0}', sort = '{}', skip = 0, limit = 0)






Read more articles


General Knowledge



Learn Popular Language