MongoDB Create Collection
Collections are containers for documents in MongoDB, similar to tables in relational databases but without requiring a predefined schema.
Creating Collections
Method 1: Implicit Creation (Recommended)
Collections are created automatically when inserting documents:
Method 2: Explicit Creation
Use the createCollection() method:
Method 3: Creation with Options
Collection Options
Common Options
Creating Collection with Validation
Collection Naming Rules
Naming Conventions
- Cannot be empty string
- Cannot contain
\0(null character) - Cannot start with
system.(system reserved) - Cannot contain
$character - Recommended: lowercase letters with underscores
Valid Names
Invalid Names
Viewing Collections
List All Collections
Get Collection Statistics
Check if Collection Exists
Capped Collections
Characteristics
- Fixed size, circular overwrite when full
- Automatically maintains insertion order
- Suitable for logs, caches, etc.
Creating Capped Collection
Querying Capped Collections
Converting Regular to Capped Collection
Collection Operation Examples
Complete Example
Modifying Collections
Modify Validation Rules
Collection Information
Get Collection Details
Best Practices
1. Naming Conventions
2. Collection Design
3. Use Validation
Summary
Key points for creating collections:
- Usually use implicit creation (auto-created when inserting documents)
- Capped collections are suitable for log-like data
- Can use validation rules to ensure data quality
- Follow naming conventions for maintainability
In the next chapter, we will learn about MongoDB Drop Collection.