Search code examples
rmongodbrmongodbmongolitermongo

How to list mongodb collections in R


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


Solution

  • 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
    
    }