MongoDB Create Database
MongoDB USE DATABASE Command is used not only to select a Database for running queries on, but also to create a Database. If the database name provided to the USE Database command is not already present in MongoDB, a new database with the name is created when you insert a Document to a Collection in that database.
Example to Create a MongoDB Database
Following is an example where we shall try creating a database named tutorialkart.
Open Mongo Shell and follow the commands in sequence.
switched to db tutorialkart
"acknowledged" : true,
"insertedId" : ObjectId("59e35d0579e9f2919b32d13d")
Following is the explanation for each mongodb command we executed above
- show dbs there are two databases already, admin and local.
- use tutorialkart switched to tutorialkart database.
- show dbs but tutorialkart is not actually created yet.
- db.users.insertOne() makes a check if the database is present. If database is not present, it creates one with the name of database that has been switched to (in step 2) and inserts the Document into the database.
- show dbs now there are three databases, including our newly created tutorialkart database.
In this MongoDB Tutorial – MongoDB Create Database, we have learnt to create a database using an example scenario.