jeroen / mongolite

Fast and Simple MongoDB Client for R
https://jeroen.github.io/mongolite/
284 stars 64 forks source link

Allow to pass literal JSON string #185

Closed ColinFay closed 4 years ago

ColinFay commented 4 years ago

Hello,

When I do things in Mongo, I'll first try to write my query in MongoDB Compass with the cli. So, in literal JSON.

When I get back to R, I can't pass this very same string to mongo$find().

Here's a reprex:

library(mongolite)
con <- mongo()
con$insert(
  list(
    name = "colin"
  )
)
#> List of 6
#>  $ nInserted  : int 1
#>  $ nMatched   : int 0
#>  $ nModified  : int 0
#>  $ nRemoved   : int 0
#>  $ nUpserted  : int 0
#>  $ writeErrors: list()
con$find("{'name' : 'colin'}")
#> Error: Invalid JSON object: {'name' : 'colin'}

Created on 2019-10-03 by the reprex package (v0.3.0)

This works in CLI / compass:

Screenshot 2019-10-03 at 12 11 14

As far as I see, it's due to the fact that {jsonlite} is unable to convert the string to JSON.

I wonder if we could have something like con$find("{'name' : 'colin'}", literal = TRUE) to be able to do that?

jeroen commented 4 years ago

The problem is that your query string is invalid JSON because json may only use double quotes to enquote a string, and you are using single quotes. Perhaps Compass is a bit more lenient, but in jsonlite you need to use proper json!

Can you try this:

con$find('{"name" : "colin"}')
ColinFay commented 4 years ago

Ah, indeed, that does work.

Thanks for the answer! Closing then.