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
Example
Verify Database Creation
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
Invalid Naming Examples
Viewing Databases
List All Databases
View Current Database
Get Database Statistics
Example output:
Switching Databases
Database Operation Examples
Complete Example Flow
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
Separation by Function
Separation by Tenant (Multi-tenant)
Best Practices
1. Naming Conventions
2. Documentation
3. Permission Planning
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.
Q: How to rename a database?
A: MongoDB has no direct rename command. You need to:
- Export using
mongodump - Restore to new name using
mongorestore
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:
usecommand 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.