MongoDB Create Database

MongoDB Create Database – In this MongoDB Tutorial, we shall learn to create a MongoDB Database dynamically.

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 1 – 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.

> show dbs;
admin  0.000GB
local  0.000GB
> use tutorialkart
switched to db tutorialkart
> show dbs;
admin  0.000GB
local  0.000GB
> db.users.insertOne( { name: "Foo", age: 34, cars: [ "BMW 320d", "Audi R8" ] } )
	"acknowledged" : true,
	"insertedId" : ObjectId("59e35d0579e9f2919b32d13d")
> show dbs;
admin         0.000GB
local         0.000GB
tutorialkart  0.000GB

Following is the explanation for each mongodb command we executed above

  1. show dbs  there are two databases already, admin and local.
  2. use tutorialkart  switched to tutorialkart database.
  3. show dbs  but tutorialkart is not actually created yet.
  4. 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.
  5. show dbs  now there are three databases, including our newly created tutorialkart database.


In this MongoDB TutorialMongoDB Create Database, we have learnt to create a database using an example scenario.