Escaping metacharacters in Regex with MongoDB (via mongolite package)

85 views Asked by At

I was querying some data via R by using mongolite and I faced a strange problem, which I eventually solved even though I cannot understand in deep way the why it works. I wanted to filter all fields with 78.20 string (no matter what's next; so the regex works fine for me).

\\ query in mongo: works
db.getCollection("exper").find({"index.tgh": /^78\.20.*/ })

\\ query via mongolite: works but only with the 4 backslashes
query <- '{"index.tgh": {"$regex": "^78\\\\.20.*"}}'
ext_1 <- database$find(query = query, fields = '{}')

Now, I understand that I had to escape the dot, so I placed a backslash in mongo. At the same time, I understand I have to escape the backslash itself in R and then I placed another slash.

What I cannot understand is why I needed two more backslashes to let the query work properly via mongolite... a third one I can foresee as escape the escaping (which in R is itself a special characther). Still do not understand the fourth one.

Thank you

0

There are 0 answers