DEV Community

Mahesh K
Mahesh K

Posted on • Edited on

R Language : Connect to MongoDB Database

Let's learn how to connect MongoDB database with R. MongoDB stores the data in the document with dynamic schemas. These days many people make use of the document-based noSQL database when they want to deal with large volume of non relational data.Coming back to the topic of connecting with the database from the R lang.

The first thing that we are going to do is we are going to check some of the drivers available for the R lang to connect with mongodb. The driver we are going to make use of in the examples below is Rmongo. You can check out the R mongo documentation from the github page.

You can check the video instruction here. R Language : Connect to MongoDB Database.

Step 1. Install the Drivers

In between the mongolite and Rmongo. I am choosing the RMongo. You may want to read the github page of mongolite if you wish to use the specific driver for the connection.

Let's assume you want RMongo. So let's install it.

install.packages("RMongo")
Enter fullscreen mode Exit fullscreen mode

That should take care of the installation part.

Step 2. Create Connection

To establish the connection we have to first use the package. And then make the connection. So let's make use of the following lines of code for the same.

library(RMongo)
rmng <- mongoDbConnect('db')
Enter fullscreen mode Exit fullscreen mode

or you can also use.

rmng <-  mongoDbConnect('db', 'localhost', 27017)
Enter fullscreen mode Exit fullscreen mode

This should help connect with the databae 'db' in the mongodb database. Next thing would be to print out the connection objects response.

Step 3. Check the server response.

To verify that the connection is established and there does not seem to be any errors, you may want to try out the following code.

print(dbShowCollections(rmng))
Enter fullscreen mode Exit fullscreen mode

This output should show you the connection response.

Step 4. Explore the specific queries

Where to go from here? Now from here onwards you have to make queries specific to your database items stored in the document. All that you do from here onwards would be specific to your database. And may require additional code for the operation.

You may want to read more about the queries from the Rdocumentation for Rmongo.

Additional references:

  1. You can also learn how to Connect R language to MySQL database.
  2. Learn How to connect to SQLite from R Language.
  3. Learn How to connect to CouchDB from R Language

Top comments (0)