Search code examples
rmongolite

Create new MongoDB database from within R using mongolite


I have a MongoDB that I connect to using the mongolite R package. In that MongoDB I would like to create a new database so that I can create collections within it.

Using the command line this seems to be possible by using the "use" command (see https://www.mongodb.com/basics/create-database)

Does anyone have an idea how / if it is possible to create a database from within R using mongolite?


Solution

  • This is indeed possible. MongoDB only creates a new database if you switch to the context of a non-existing database and then insert data into it. Using mongolite, you can connect to a non-existing database and collection and insert data and that database and collection will be created automatically.

    So you just do the following:

    library(mongolite)
    mongo_con <- mongolite::mongo(collection = "your_new_collection", url = "mongodb://your_user:your_password@your_server:your_port/your_new_database?authSource=your_authentication_database")
    mongo_con$insert(some_data)