Skip to main content

Databases in MongoDB are created "on the fly"

MongoDB does not require explicit database creation. Databases in MongoDB are created "on the fly" when you first store data within a collection inside that database.
Here's how this process works:
  • Switch to the desired database: In the MongoDB shell, use the use command followed by the name you want for your database. For example:
Code
    use myNewDatabase
If myNewDatabase does not exist, MongoDB will switch to it, but it won't be physically created until data is inserted. If it already exists, you will simply switch to it.
  • Insert data into a collection: Once you have switched to your desired database, insert a document into a collection. If the collection does not exist, MongoDB will create it automatically when the first document is inserted. For example:
JavaScript
    db.myCollection.insertOne({ name: "Alice", age: 30 });
In this example, if myNewDatabase didn't exist before, it will now be created, and myCollection will also be created within it, containing the inserted document.
In summary: You don't "create" a MongoDB database in the traditional sense with a dedicated command. You simply use a database name, and it comes into existence when you first populate a collection within it