Create Database

Create a MongoDB Database

Creating a database in MongoDB is unique. You do not use a strict CREATE statement. MongoDB handles this automatically for you.

The "use" Command

In the MongoDB shell, you switch databases. You use the use command followed by a name. If the database does not exist, MongoDB prepares it.

Lazy Creation

MongoDB uses a lazy creation strategy. The database isn't actually saved immediately. It is only saved when you insert data into it.

Checking Databases

You can list databases using show dbs. If your new database is empty, it won't appear. You must add at least one document first.

Naming Rules

Database names cannot be empty. They cannot contain spaces or special symbols. Keep names short and descriptive.

Default Databases

MongoDB comes with some default databases. The admin database holds user roles. The local database stores replication data.

MongoDB Shell Commands:

// Switch to a new database
use myNewDatabase

// Insert a document to force creation db.myCollection.insertOne({ init: true })

// Check the list of databases show dbs

Dropping a Database

Sometimes you need to delete a database. You must switch to it first. Then run db.dropDatabase().

Security Considerations

Always protect your databases. Do not give default users admin rights. Use MongoDB Atlas for built-in network security.

Summary

Creating databases requires no boilerplate. Just "use" it and insert data. MongoDB's lazy creation speeds up workflows.

Practice

Open your MongoDB shell today. Try creating a test database right now.

Exercise

When is a new database actually saved to the disk in MongoDB?