2

I have been trying to list collections within a mongo database in R. I have realized that this feature is still in the to do list in the mongolite package (https://github.com/jeroen/mongolite/issues/86). There seemed to be a package, rmongodb, which did the trick (Unable to see all collections from a mongodb remote server using mongolite). However, it is no longer a part of CRAN.

Can anyone, please, suggest a way to list all collection in a database?

The mongodb is remote, so I guess using the mongoshell with combination with system() is not an option. At least not a straightforward one.

Thanks

deann
  • 756
  • 9
  • 24
  • `rmongodb` is available on github. And it's easy to get what you need with this package. [link](https://gist.github.com/Btibert3/7751989) – Juan Antonio Roldán Díaz Jun 19 '18 at 09:47
  • Yes, but it seems to be discontinued. Why is it off cran? – deann Jun 19 '18 at 10:04
  • Its developers stopped maintaining it, and it has some obsolete drivers, but they can use the parts of the package that you need and they work correctly, and if you have any problems you can report them in Github. [Read more](https://github.com/dselivanov/rmongodb#project-status) – Juan Antonio Roldán Díaz Jun 19 '18 at 10:17
  • 2
    I believe the latest version of `mongolite` now has the `run()` feature. – SymbolixAU Aug 13 '18 at 22:34

1 Answers1

1

The solution I came up with is the following:

ListMongoCollections <- function(db, mongoConString) {

  result <- system(glue::glue(
    "
    mongo --host <<mongoConString>> --eval \"
      db.getMongo().getDBNames().forEach(
        function(v, i) {if (v.valueOf() === '<<db>>') {
          print(db.getSiblingDB(v).getCollectionNames().join('%%%'))
        }}
      )
    \"
    ",
    .open = "<<",
    .close = ">>"
    ),
    intern = T
  )

  collections <- result %>% stringr::str_detect("%%%")

  result <- result[collections] %>% 
    stringr::str_split(pattern = "%%%", simplify = T) %>% 
    as.character()

  result

}
deann
  • 756
  • 9
  • 24
  • 3
    There is a new method to list collections implemented in the mongolite library described here: https://jeroen.github.io/mongolite/server-tools.html#running-commands – deann Sep 21 '18 at 13:08
  • 2
    The solution at the link worked for me. It basically asks you to run the "query": `col$run('{"listCollections":1}')`. Thanks. – Relevance Apr 19 '21 at 05:26