Skip to content

MongoDB Create Database

Creating a database in MongoDB is very simple. You don't need an explicit create command; just use the use command to switch to a non-existent database, then insert data.

Creating a Database

Basic Syntax

javascript
use database_name

Example

javascript
// Switch to mydb database (creates if doesn't exist)
use mydb

// View current database
db
// Output: mydb

Verify Database Creation

javascript
// Insert data for the database to actually be created
db.users.insertOne({ name: "John", age: 25 })

// View all databases
show dbs
// Output:
// admin   0.000GB
// config  0.000GB
// local   0.000GB
// mydb    0.000GB  ← Newly created database

Database Naming Rules

Naming Conventions

  • Cannot be an empty string
  • Cannot contain spaces, ., $, /, \, and \0 (null character)
  • Should be all lowercase (recommended)
  • Maximum 64 bytes
  • Cannot conflict with system reserved names

Reserved Database Names

  • admin: Authentication and authorization database
  • local: Local data storage, not replicated
  • config: Sharded cluster configuration information

Valid Naming Examples

javascript
use mydb           // ✓ Valid
use my_database    // ✓ Valid
use db123          // ✓ Valid
use userData       // ✓ Valid (but mixed case not recommended)

Invalid Naming Examples

javascript
use my.db          // ✗ Contains dot
use my$db          // ✗ Contains dollar sign
use my db          // ✗ Contains space
use admin          // ⚠️ System reserved (usable but not recommended)

Viewing Databases

List All Databases

javascript
show dbs
// Or
show databases

View Current Database

javascript
db

Get Database Statistics

javascript
db.stats()

Example output:

json
{
  "db": "mydb",
  "collections": 2,
  "views": 0,
  "objects": 5,
  "avgObjSize": 45.2,
  "dataSize": 226,
  "storageSize": 36864,
  "indexes": 2,
  "indexSize": 36864
}

Switching Databases

javascript
// Switch to test database
use test

// Switch to admin database
use admin

// Switch back to mydb
use mydb

Database Operation Examples

Complete Example Flow

javascript
// 1. Create/switch to new database
use company

// 2. Create collection and insert data
db.employees.insertOne({
  name: "John",
  department: "Engineering",
  salary: 5000,
  hireDate: new Date()
})

// 3. Create another collection
db.departments.insertOne({
  name: "Engineering",
  manager: "John",
  location: "3rd Floor"
})

// 4. View database list
show dbs

// 5. View current database statistics
db.stats()

Database Size Limits

Theoretical Limits

  • Namespace file size: Default 16MB (configurable)
  • Collection count: Limited by namespace, approximately 12,000
  • Database count: No hard limit (limited by file system)

Practical Considerations

  • File system limitations
  • Hardware resources (disk space, memory)
  • Management complexity

Multi-Database Architecture Design

Separation by Environment

myapp_dev      // Development environment
myapp_test     // Testing environment
myapp_prod     // Production environment

Separation by Function

myapp_users    // User data
myapp_orders   // Order data
myapp_logs     // Log data

Separation by Tenant (Multi-tenant)

tenant_a_data  // Tenant A data
tenant_b_data  // Tenant B data
tenant_c_data  // Tenant C data

Best Practices

1. Naming Conventions

javascript
// Recommended: lowercase letters, underscore separation
use ecommerce_db
use user_service_db

// Not recommended
use EcommerceDB      // Mixed case
use ecommerce-db     // Using hyphens

2. Documentation

javascript
// Create documentation document in database
db.metadata.insertOne({
  description: "User service database",
  created: new Date(),
  owner: "Engineering Team",
  purpose: "Store user information and authentication data"
})

3. Permission Planning

javascript
// Create separate users for different databases
use admin

db.createUser({
  user: "ecommerce_app",
  pwd: "password",
  roles: [
    { role: "readWrite", db: "ecommerce_db" }
  ]
})

Common Questions

Q: Created database but can't see it with show dbs?

A: Empty databases are not displayed; they become visible after inserting data.

javascript
use newdb
show dbs          // Can't see newdb

db.test.insertOne({})  // Insert data
show dbs          // Now can see newdb

Q: How to rename a database?

A: MongoDB has no direct rename command. You need to:

  1. Export using mongodump
  2. Restore to new name using mongorestore
bash
# Export original database
mongodump --db oldname --out /backup/

# Restore to new database
mongorestore --db newname /backup/oldname/

# Drop original database
mongosh --eval "db.getSiblingDB('oldname').dropDatabase()"

Q: How to modify database configuration after creation?

A: Database-level configuration is minimal; mainly through:

  • Collection-level configuration
  • Server configuration file
  • Runtime parameters

Summary

Characteristics of MongoDB database creation:

  • Lazy creation: use command doesn't immediately create the database
  • Automatic creation: Created automatically on first data insertion
  • Flexible naming: Follows simple naming rules
  • Lightweight: Low creation cost, can create multiple databases as needed

In the next chapter, we will learn about MongoDB Drop Database.

Content is for learning and research only.