I am facing an issue while querying mongodb from R(using rmongodb package) using regular expressions. Below is my code:
buf <- mongo.bson.buffer.create()
regex <- mongo.regex.create("air filter*$", options="i")
mongo.bson.buffer.append.regex(buf, "keyword", regex)
query <- mongo.bson.from.buffer(buf)
res <- mongo.find.all(mongo,collection,query)
But I get empty result in 'res' from the DB. However, when I check the regex in the DB directly, it gives me valid results. When I give the keyword name without regular expressions in the above query (eg: "air filter")
,it works fine.
I have tried all possible combinations but in vain.
Following are the example docoments
[
{
"_id":ObjectId("55dcdc72473fdf86c0020d96"),
"_class":"",
"keyword":"air filter",
"synonyms":[
]
},
{
"_id":ObjectId("55dcdc72473fdf86c0020e0f"),
"_class":"",
"keyword":"cabin air filter",
"synonyms":[
]
},
{
"_id":ObjectId("55dcdc79473fdf86c002143b"),
"_class":"",
"keyword":"secondary air filter",
"synonyms":[
]
}
]
Note: I have tried json string but cannot use since I need to pass variable as input regex,i.e. I create the regex using paste0(component[1], "*$")
where component list contains the terms like air filter,etc.
Could you kindly provide some guidance?
Thanks!
Here is what I tried and it is working
library(rmongodb)
mongo <- mongo.create(host = "localhost", db = "test")
components <- list("air filter", "engine oil")
for (component in components) {
jsonStr <- paste0('{"keyword" : {"$regex" : "', component, '$"}}')
mongo.bson.from.JSON(jsonStr)
res <- mongo.find.all(mongo, "test.coll", mongo.bson.from.JSON(jsonStr))
print(res)
}