In MongoDB, databases are created implicitly when you first insert data into them. MongoDB creates a database as soon as you insert a document into a collection within that database. However, you can also explicitly create a database using the use command or the getDB method.
Using use Command:
-
Open a MongoDB shell by running the
mongoshcommand in your terminal. -
Use the
usecommand to switch to a specific database. If the database doesn't exist, MongoDB will create it.use your_database_name
Replace
your_database_namewith the desired name for your database. -
You can now start inserting documents into collections within the specified database, and MongoDB will create the database if it doesn't exist.
Using getDB Method:
-
Open a MongoDB shell.
-
Use the
getDBmethod to explicitly create a database and switch to it.db = db.getSiblingDB('your_database_name')Replace
your_database_namewith the desired name for your database. -
You can now start inserting documents into collections within the specified database.
Inserting a Document to Create the Database:
If you want to create a database without explicitly switching to it, you can insert a document into a collection in the desired database. MongoDB will create the database if it doesn't exist.
use your_database_name
db.your_collection_name.insert({ key: 'value' })
Replace your_database_name with the desired name for your database, and your_collection_name with the desired name for your collection.

Comments