Read and Write Files From MongoDB With R
-
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
andCyrus SASL
. Under Debian or Ubuntu, uselibssl-dev
andlibsasl2-dev
:if (!require(mongolite)) { # Install system dependencies system("sudo apt-get install -y libssl-dev libsasl2-dev") install.packages("mongolite") library(mongolite) }
-
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
is27017
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. -
-
You can now:
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.
See also