rmongodb query combining AND, OR, and string match

201 Views Asked by At

Apologies if this has already been addressed.

In mongodb, I have a database collection called "main." I can successfully run the following query from a mongodb shell:

        db.main.find( {
    $or : [
        { $and : [ { "Var1Path": /.*20072.*/ }, { "Var2Path": /.*30033.*/ } ] },
        { $and : [ { "Var1Path": /.*30033.*/ }, { "Var2Path": /.*20072.*/ } ] },
    ]
} )

I seek to run the same query in R with rmongodb. The query combines AND and OR. The slashes act as a string match (e.g., find the string '20072' anywhere in the field called Var1Path). Can this be run in R with rmondodb? If so, how should it be written?

1

There are 1 best solutions below

0
On BEST ANSWER

Did you try to write some code / read rmongodb vignettes?
You need soomething like this:

and_1 = list("$and" = list( list("Var1Path" = list("$regex" = "20072" )), 
                            list("Var2Path" = list("$regex" = "30033" )) ))
and_2 = list("$and" = list( list("Var1Path" = list("$regex" = "30033" )), 
                            list("Var2Path" = list("$regex" = "20072" )) ))
mongo.find(mongo = mongo, ns = 'db_name.collection_name', 
           query = list("$or" = list(and_1, and_2)))

One thing all rmongodb users should remeber: there is very straightforward mapping between mognodb objects and R objects - unnamed lists parsed as arrays and named lists parsed as objects.