MongoDB Create Database with mongosh
MongoDB create database usually means selecting a database name with the use command and then storing data in it. MongoDB does not permanently create an empty database only because you switched to that name. The database appears in show dbs after you create a collection or insert the first document.
In this MongoDB Tutorial, we shall learn to create a MongoDB Database dynamically using mongosh, verify it, and understand why a newly selected database may not appear immediately.
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.
How MongoDB Creates a Database When Data Is Stored
The important point is that use databaseName only changes the current database context. MongoDB creates the database on disk after the first write operation, such as inserting a document or creating a collection. This behavior is useful for quick development, but it also means that spelling mistakes in database names can create unexpected databases when a write operation is run.
show dbslists databases that already contain data or collections.use tutorialkartswitches the shell to thetutorialkartdatabase name.db.users.insertOne(...)creates theuserscollection and stores the first document.- After the first write,
show dbsdisplays the new database.
For reference, MongoDB documents the database and collection model in its official Databases and Collections manual page, and insert operations in the Insert Documents guide.
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
- 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.
Verify the Current MongoDB Database and Collection
After creating the database, check the current database name, list collections, and read the inserted document. These checks help confirm that the write happened in the intended database.
db
show collections
db.users.find()
The db command shows the database currently selected in mongosh. The show collections command should display users. The find() command reads documents from the collection.
tutorialkart
users
[
{
_id: ObjectId("59e35d0579e9f2919b32d13d"),
name: 'Foo',
age: 34,
cars: [ 'BMW 320d', 'Audi R8' ]
}
]
Create a MongoDB Database by Creating a Collection First
You can also create the database by explicitly creating its first collection. This is useful when the collection needs options such as validation rules, collation, capped collection settings, or time series settings. MongoDB explains this method in the official db.createCollection() reference.
use tutorialkart_explicit
db.createCollection("users")
show dbs
show collections
For most beginner examples, inserting the first document is enough. Use db.createCollection() when you need to define collection behavior before the first insert.
Create a MongoDB Database with Validation Rules
MongoDB is flexible, but a new application often needs some basic rules for important fields. The following example creates a database and a users collection with a simple JSON schema validator before inserting data.
use tutorialkart_validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "age"],
properties: {
name: {
bsonType: "string",
description: "name must be a string"
},
age: {
bsonType: "int",
minimum: 0,
description: "age must be a non-negative integer"
}
}
}
}
})
db.users.insertOne({
name: "Foo",
age: 34
})
This approach is different from simply running use tutorialkart_validation. The database becomes visible only after the collection is created successfully.
Create a MongoDB Database in Node.js
When you use MongoDB from Node.js, you normally create a database by connecting to the server, selecting a database with client.db("databaseName"), and writing the first document to a collection.
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db("tutorialkart_node");
const users = db.collection("users");
const result = await users.insertOne({
name: "Foo",
age: 34
});
console.log("Inserted document id:", result.insertedId);
} finally {
await client.close();
}
}
run().catch(console.error);
The database name is tutorialkart_node. The collection name is users. The first successful insert creates both if they do not already exist.
MongoDB Atlas and Compass Database Creation Notes
If you are using MongoDB Atlas or MongoDB Compass instead of mongosh, the idea is the same: a database needs at least one collection. In Atlas, the database creation screen asks for both a database name and a collection name. In Compass, you can create a database from the visual interface and provide the first collection name there.
Use mongosh examples when you are learning commands or writing scripts. Use Atlas or Compass when you prefer a visual interface for creating the first database and collection.
Common MongoDB Create Database Mistakes
- Expecting an empty database in
show dbs: a database selected withuseis not listed until data or a collection is created. - Typing the wrong database name: MongoDB can create a new database with the mistyped name after a write operation.
- Inserting into the wrong collection: check
dbandshow collectionsbefore running important inserts. - Using
db.createCollection()for every collection: it is optional unless you need specific collection options. - Testing with old shell syntax: prefer
mongoshand modern methods such asinsertOne()for new examples.
MongoDB Create Database Command Reference
| Task | MongoDB command | What it does |
|---|---|---|
| List databases | show dbs | Displays databases that already contain data. |
| Select or name a database | use tutorialkart | Switches the current shell context to the database name. |
| Create database by inserting data | db.users.insertOne({...}) | Creates the database and collection if they do not exist. |
| Create collection explicitly | db.createCollection("users") | Creates the first collection, which makes the database visible. |
| List collections | show collections | Shows collections in the selected database. |
| Read inserted documents | db.users.find() | Returns documents from the users collection. |
Editorial QA Checklist for MongoDB Create Database Examples
- Confirm that every
usecommand is followed by a write operation ordb.createCollection()before saying the database exists. - Check that sample database names and collection names are consistent across commands and explanation text.
- Use
insertOne()in new examples instead of older insert syntax. - Show verification commands such as
show dbs,show collections, anddb.collection.find(). - Mention Atlas or Compass only when the instruction needs a visual database creation path.
MongoDB Create Database FAQs
Does MongoDB automatically create a database?
MongoDB creates a database automatically when you first store data in it, such as by inserting a document or creating a collection. Running use databaseName alone only selects the database name.
Why does my MongoDB database not show after the use command?
The database does not show because it is still empty. Insert a document or create a collection, and then run show dbs again.
Can I create a MongoDB database for free while learning?
For local learning, you can install MongoDB Community Server and create databases on your machine. If you use MongoDB Atlas, check the current cluster options available in your account before creating a database.
How do I create a MongoDB database in Node.js?
Connect with the MongoDB Node.js driver, select a database using client.db("databaseName"), and insert the first document into a collection. The write operation creates the database if it does not already exist.
Should I use db.createCollection() or insertOne() to create a MongoDB database?
Use insertOne() for a simple first document. Use db.createCollection() when the collection needs options such as validation, collation, capped collection settings, or other collection-level rules.
MongoDB Create Database Key Points
In this MongoDB Tutorial – MongoDB Create Database, we have learnt to create a database using an example scenario. The key point is that MongoDB creates a database after the first collection or document is stored, not merely after the use command. For a simple database, select the name, insert the first document, and verify the result with show dbs and show collections.
TutorialKart.com