R MongoDB Database Connection
MongoDB is a NoSQL open source document-oriented database management system. This is suitable for modern internet applications. It provides dynamic queries, scalability, secondary indexes, fast atomic updates. We can easily use more than one databases.
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 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 like, 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.
mongo$find()
mongo$find('{"cyl" : 6, "mpg" : { "$gt" : 20}}')
MongoDB Update data
The mongo$update() method updates the data in a collection.
mongoID <- "5755f646ceeb7846c87afd90"
## to add a single value to an array
mongo$update(query = paste0('{"_id": { "$oid" : "', mongoID, '" } }'),
update = '{ "$addToSet" : { "value_array" : "checkedByR" } }')
MongoDB Count data
The mongo.count() method counts the number of documents in a collection.
# Count the number of documents in the collection
mongo$count()