How do I pass strings into a function that makes mongolite queries?

249 Views Asked by At

I have to make many mongoengine queries, so I tried to write a function that would allow me to repeat myself less often. The basic code to run for a query is:

library(mongolite)    
m <- mongo('test', 'test', url = testurl)
mydata <- m$find('{"field1": "foo", "field2": "bar"}')

And my function is:

get_mongo_data <- function(field1, field2, mongoconnection = m){
  mongo_string = toJSON(paste0('\'{\"field1": \"', field1,
                               '\", "field2": \"', field2, '\"}\''))
  dataset <- mongoconnection$find(mongo_string)
  return(dataset)
}

But when I try to use it, it fails.

mydata <- get_mongo_data('foo', 'bar') # fails

To see what's going on, I looked at what my function was actually passing to the query:

> (mongo_string = toJSON(paste0('\'{\"field1": \"', field1,
                                '\", "field2": \"', field2, '\"}\'')))
["'{\"field1\": \"foo\", \"field2\": \"bar\"}'"] 

I can see that it doesn't match. It adds a [" to both sides of the string. However, without the toJSON function, I get Error: Invalid JSON object: '{"field1": "foo", "field2": "bar"}'

Is there any way to pass strings into a JSON object in this way, so that I can write a function that takes strings and returns the result of a mongolite query?

1

There are 1 best solutions below

0
On BEST ANSWER

I found a solution. I removed the toJSON() call, and removed what I assumed was a necessary ' at both ends of the string. The following code works.

library(mongolite)    
m <- mongo('test', 'test', url = testurl)
mydata <- m$find('{"field1": "foo", "field2": "bar"}')

get_mongo_data <- function(field1, field2, mongoconnection = m){
  mongo_string = paste0('{\"field1": \"', field1,
                        '\", "field2": \"', field2, '\"}')
  dataset <- mongoconnection$find(query = mongo_string)
  return(dataset)
}

mydata <- get_mongo_data('foo', 'bar') # succeeds