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
opensslandCyrus SASL. Under Debian or Ubuntu, uselibssl-devandlibsasl2-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:
-
usermust be replaced with your username. -
passwordmust be replaced with your password. -
ipmust be replaced with your IP address. -
portis27017by default. -
authentificationDatabasemust be replaced with the authentication database.The authentication database is sometimes different from the database where the collections are located. -
collectioncan be a new collection to create. -
databasemust 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
datamust be replaced with the data to write to MongoDB.
See also