Read and Write Files From MongoDB With R

How to read and write files from MongoDB with R using the mongolite package.

  1. Install the mongolite package to interact with MongoDB.
    For more information, see https://CRAN.R-project.org/package=mongolite.

    Installation from source under Linux requires openssl and Cyrus SASL. Under Debian or Ubuntu, use libssl-dev and libsasl2-dev:

    if (!require(mongolite)) {
     # Install system dependencies
     system("sudo apt-get install -y libssl-dev libsasl2-dev")
     install.packages("mongolite")
     library(mongolite)
    }
  2. Connect to MongoDB by running the following lines of code:

    # ====== Connection to MongoDB ====== #
    # To build the connection URI from the above parameters.
    uri <- paste0("mongodb://", user, ":", password, "@", ip, ":", port, "/", authentificationDatabase)
    
    # To connect to the database.
    con <- mongo(collection = collection, db = database, url = uri)

    Where:

    • user must be replaced with your username.

    • password must be replaced with your password.

    • ip must be replaced with your IP address.

    • port is 27017 by default.

    • authentificationDatabase must be replaced with the authentication database.

      The authentication database is sometimes different from the database where the collections are located.
    • collection can be a new collection to create.

    • database must be replaced with the database where the collections are located.

    If there are special characters in the username or password, see the conversion table.
  3. You can now:

    • Count the Number of Document in the Collection

    • Insert New Data in the Collection

    • Read Data From the Collection

    • Read Data From Any Valid MongoDB Query

    con$count()
    con$insert(data)
    con$find()
    con$find('{"cyl" : 6, "mpg" : { "$gt" : 20}}')

    Where data must be replaced with the data to write to MongoDB.