Search code examples
rmongodbmongolite

Why is my code unable to connect to Mongo DB?


I am trying to point my R code to my mongodb.

I have a config.yml:

default:
    host:    "cluster0.qixym.mongodb.net"
    username: "****"
    password: "****"
    
production:
    host:     "cluster0.qixym.mongodb.net"
    username: "****"
    password: "****"

Here is my code:

# MONGO DB TRAINING -----
# Version 1
# LIBRARIES ----
library(mongolite) # Resource: https://jeroen.github.io/mongolite/
library(jsonlite)
library(config)
library(tidyverse)
library(lubridate)

# 1.0 CONNECTION TO REMOTE MONGODB ----

# Setup config Package & database YAML
Sys.setenv(R_CONFIG_ACTIVE = "default")

config <- config::get(file = "config.yml")



mongo_connect <- function(collection, database, 
                          username = config$username, 
                          password = config$password, 
                          host = config$host){
  
  mongo(
    collection = collection, 
    url = str_glue("mongodb+srv://{username}:{password}@{host}/{database}/?tls=true"), 
    options = ssl_options(weak_cert_validation = T)
    
    )
  
}



# Connect to MongoDB Atlas Cloud Database
mongo_connect(collection = "mtcars", database = "rstats")

I get the following error:

** Error in (function (uri = "mongodb://127.0.0.1", pem_file = NULL, pem_pwd = NULL, : failed to parse URI: p (Invalid database name in URI) **

I did look at this thread but could not find a solution: https://github.com/jeroen/mongolite/issues/219


Solution

  • So the code above works!

    The issue was that I had special characters in my password!

    https://docs.mongodb.com/manual/reference/connection-string/#components