简体   繁体   中英

Rmongodb using regex does not work as expected

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,ie 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM