I have to retrieve data from a Mongo DB collection given a particular condition based on a variable value in R. I could find documentation on querying with static values in RMongo. But I could not find how to query using variable values. I tried the below query to retrieve documents from a collection for which the value of the field 'emailId' is equal to that of the variable 'contact'. dbGetQuery(mongo, "name of collection", '{"emailId":"${contact}"}') This query returns 0 rows since it considers '${contact}' as a string. I tried using it without quotes. But that gave error. I found a similar question in stack overflow for rmongodb package. But since I am using RMongo, I need a solution that applies to Rmongo.
Asked
Active
Viewed 541 times
1
-
paste function in R? I don't understand how it will be useful here. I need to use a variable value in R to query a mongoDB collection using dbGetQuery. All examples of dbGetQuery contain constant values only as in the below query. dbGetQuery(mongo, "test_data", '{"foo": "bar"}') In this query, 'bar' is a constant. How should I query if I need to use the value in a variable named 'bar'? – avidlearner Apr 03 '16 at 12:10
-
1` dbGetQuery(mongo, "test_data", paste0('{"foo": "', bar, '"}')` You have to create the query string. Use the `paste` function with whatever variables you'd like. – cory Apr 03 '16 at 18:55
-
This worked! Thank you! – avidlearner Apr 04 '16 at 08:31
-
The query has been working for character variables. But it is not working for numeric variables. Is there any changes that need to be made in the query specifically for numeric variables? – avidlearner Apr 16 '16 at 06:45
-
1Yeah, you probably have to get rid of the quotes... when you paste together your query from above, `bar` is in quotes. Maybe mongo wants numeric values to have no quotes. That's my guess.... – cory Apr 17 '16 at 00:53