tc / RMongo

R client to interface with MongoDB
102 stars 34 forks source link

Can variables be used in dbInsertDocument() #26

Closed bryan3189 closed 10 years ago

bryan3189 commented 10 years ago

if I create a variable. For e.g, userid <- "123"

Can I use that variable to insert the value in the collection using the dbInsertDocument method. For e.g, dbInsertDocument(mongo, "mydata", '{"UserID": userid}')

I'm getting the following error, Error in .jcall(rmongo.object@javaMongo, "S", "dbInsertDocument", collection, : com.mongodb.util.JSONParseException: {"UserID": userid}

tc commented 10 years ago

Can you str concat the variable before passing it in?

query <- paste(c(' '{"UserID":"',  userid  , ''"}'), collapse=' ')
dbInsertDocument(mongo, "mydata",query)
bryan3189 commented 10 years ago

Hey Tommy,

The above suggestion doesn't work.

Consider the following query output <- dbGetQuery(mongo, 'test_data', '{"foo": { "$regex": "bar*", "$options": "i"} }')

Now if, c <- "bar*" output <- dbGetQuery(mongo, 'test_data', '{"foo": { "$regex": c, "$options": "i"} }')

Returns and Error. Can you please help me get this problem solved. Concatenating it before passing gave me and error.

Thank you

tc commented 10 years ago

You need to concat the whole string before passing it in to the dbGetQuery

c <- "\"bar*\""
query <- paste('{"foo": { "$regex": ',  c, ', "$options": "i"} }')
output <- dbGetQuery(mongo, 'test_data', query)
bryan3189 commented 10 years ago

Thank You Tommy. That really helped alot.