Search code examples
rmongodbmongolite

Mongodb text search in R programming


I created a MongoDB text index using R programming.

library(mongolite)
library(jsonlite)
  mn <- mongo(collection = "collname", db = "dbname", url = "mongodb://localhost:27017" )

mn$index(toJSON(list("title" = "text"), auto_unbox = TRUE))

I am trying to do MongoDB text search in R for the below code.

 mn$find(toJSON(list("$text" = list("$search" = "STORAGE")), auto_unbox = TRUE))

But, I got an output as "data frame with 0 columns and 0 rows". How, do I do it for proper output?


Solution

  • It's hard to find your error without seeing your data.

    However, this example works for me

    library(mongolite)
    
    m <- mongo(db = "mtcars", collection = "mtcars")
    
    m$insert(mtcars)
    
    m$index('{"_row":"text"}')
    
    m$find( '{"$text":{"$search":"Mazda"} }')
    
    # mpg cyl disp  hp drat    wt  qsec vs am gear carb
    # Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4
    # Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
    

    Similarly, constructing the JSON query from a list also works

    m$find( toJSON(list("$text" = list("$search" = "Mazda") ), auto_unbox = T) )
    
    # mpg cyl disp  hp drat    wt  qsec vs am gear carb
    # Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4
    # Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4