How do I query using a variable value in mongodb from R?

621 Views Asked by At

I am new in rmongodb. I would like to make a query in one collection in MongoDB using the value of a variable. It goes like this:

 OBS_ID<-"20150510120000"

 QUERY_DATA<-mongo.find.all(MONGO, "prod.CUSTDATA", query='{"Obs_ID" :
 OBS_ID}')

This code doesn't work. I can not find any related documentation in rmongodb on how to deal with this.

Looking forward for your answers! Thank you!

3

There are 3 best solutions below

0
On

The following worked for me, although I am using mongolite, the idea may be useful for you:

   library (mongolite)
   con = mongo(...) #your data to connect to your mongoDB
   fquery <- (paste0("{\"","Obs_ID\"",":\"", OBS_ID, "\"}")) #create the query
   mydata <- con$find(fquery) #retrieve data

Note: use ", Mongo will not accept '.

Best!

1
On

I think you should try dbGetQuery as below :

library('RMongo')
dbName <- mongoDbConnect('dbname')
query <- dbGetQuery(dbName,'collectionName',"{'Obs_ID' : '20150510120000'}")
0
On

I have already found the solution to this problem. I need to create a mongo.bson.buffer object.

Set up the query

OBS_ID<-"20150510120000"

buf <- mongo.bson.buffer.create() mongo.bson.buffer.start.object(buf,"Obs_ID") mongo.bson.buffer.append(buf,"$eq",OBS_ID) criteria <- mongo.bson.from.buffer(buf)

Query from MongoDB using the criteria

QUERY<-mongo.find.all(MONGO, "prod.CUSTDATA", query=criteria)