00:00

MongoDB Create Database

Last updated: 4 min read

In a relational database you create a database with CREATE DATABASE before you can use it. MongoDB has no such command: a database comes into existence automatically the first time you store data in it.

This tutorial shows how that works in mongosh, in the graphical tools and from Java, explains the naming rules and the special system databases, and covers the mistakes beginners usually make.

1. How Databases Are Created in MongoDB

Creating a database takes two steps:

  1. Switch to the database with use <name>. This only sets the current database for your shell session.
  2. Store something in it: insert a document, create a collection or create an index. At that moment MongoDB creates the database on disk.
This lazy creation is deliberate. A typo like use bookstroe does not leave an empty database behind unless you actually write data into it.

2. Using the use Command in mongosh

mongosh
use bookstore
// switched to db bookstore

db                 // shows the current database
// bookstore

show dbs           // bookstore is NOT listed yet: it holds no data
// admin    40.00 KiB
// config   72.00 KiB
// local    80.00 KiB

Now write the first document. The database and the books collection are created together:

mongosh
db.books.insertOne({ title: "Practical Java Streams", price: 499 })
// { acknowledged: true, insertedId: ObjectId('...') }

show dbs
// admin       40.00 KiB
// bookstore   40.00 KiB      <-- now it exists
// config      72.00 KiB
// local       80.00 KiB

You can also create the database by creating an empty collection explicitly:

mongosh
use library
db.createCollection("members")
// { ok: 1 }

3. Inspecting a Database

mongosh
db.getName()               // name of the current database
show collections           // collections in the current database
db.getCollectionNames()    // the same, as an array
db.stats()                 // size, number of collections, objects, indexes
db.stats(1024 * 1024)      // the same statistics scaled to megabytes

To open a different database without changing the current one, for example inside a script, use db.getSiblingDB():

mongosh
const reports = db.getSiblingDB("reports")
reports.daily.insertOne({ day: "2026-10-18", orders: 128 })

4. Database Naming Rules

RuleDetails
LengthFewer than 64 characters
Not allowed on any platform/ \ . space " $ and the null character
Also not allowed on Windows* < > : | ?
CaseNames are case-sensitive, but two databases cannot differ only by case (Shop and shop)
Empty nameNot allowed

A good convention is short, lowercase names with words joined by underscores or hyphens, and environment-specific names where useful: bookstore, bookstore_test, analytics.

5. System Databases

Every deployment has a few databases that MongoDB uses itself. Do not store application data in them:

DatabasePurpose
adminUsers and roles with cluster-wide privileges, and administrative commands
localData specific to one server, including the replication oplog; never replicated
configSharding metadata and internal session data

6. Creating a Database in Compass or Atlas

Graphical tools follow the same rule that a database needs at least one collection:

  • MongoDB Compass: connect, click the + next to Databases (or Create database), and enter both a database name and a first collection name.
  • MongoDB Atlas: open your cluster, go to Data Explorer (Collections), choose Create Database, and again provide a database and a collection name.

7. Creating a Database from Java

With the Java driver, getDatabase() only returns a handle; nothing is created until the first write, exactly as in the shell.

CreateDatabaseExample.java
import com.mongodb.client.*;
import org.bson.Document;

public class CreateDatabaseExample {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoDatabase db = client.getDatabase("bookstore");   // no server call yet

            db.getCollection("books")
              .insertOne(new Document("title", "Document Modeling Basics").append("price", 420));

            // Now the database exists
            client.listDatabaseNames().forEach(System.out::println);
        }
    }
}

In Spring Boot, you usually name the database in the connection string, and Spring Data creates it on the first save:

application.properties
spring.data.mongodb.uri=mongodb://localhost:27017/bookstore

8. Permissions

When authentication is enabled, you need a role that allows writing to the new database, for example readWrite on that database or readWriteAnyDatabase. An application user is usually created per database:

mongosh
use admin
db.createUser({
  user: "bookstoreApp",
  pwd: passwordPrompt(),
  roles: [ { role: "readWrite", db: "bookstore" } ]
})

9. Common Mistakes

  • Expecting use to create the database. It does not appear in show dbs until it holds data.
  • Typos in database names. Because creation is automatic, use bookstroe followed by an insert silently creates a new database. Check with db before writing.
  • Different case in different services. BookStore in one service and bookstore in another fails with a "case differs" error.
  • Writing into admin or local by forgetting to switch databases first.

10. Summary

  • MongoDB has no CREATE DATABASE; a database is created when you first store data in it.
  • use <name> switches the current database; show dbs lists only databases that contain data.
  • Follow the naming rules: under 64 characters, no special characters, and no names that differ only by case.
  • admin, local and config are reserved for MongoDB itself.
  • From Java and Spring Boot, the database is created on the first write as well.