Databases and Collections: Namespace Management in MongoDB
A database is a container for collections, and a collection is a container for documents—this is the hierarchical structure of data in MongoDB.
This course provides an in-depth understanding of the concepts, naming conventions, and creation methods of databases and collections, as well as the special "capped collection."
1. What You'll Learn
- The Fundamental Difference Between Databases and Sets (Namespaces)
- The schema-less design philosophy of MongoDB collections
- Naming Conventions and Restrictions for Databases and Collections
- The Difference Between Implicit and Explicit Creation
Usage of
use,show,db.createCollection() - capped collection (circular queue)
- Collection Metadata View and Database Management
2. A True Story of a Database Administrator
(1) Pain Point: Confusing naming conventions make maintenance difficult
Diana is a MongoDB database administrator responsible for managing the company's e-commerce database. She discovered that:
"We have over 50 databases and over 500 collections, with all sorts of names:
shopdb.Products,shop-db.Products,shop-db.product_list… We don’t know which one to use when running queries, and our backup scripts often fail."
The Chaotic Current Situation:
| Issue | Impact |
|---|---|
| Inconsistent naming conventions | Team members can't find collections |
| Mixed case | MongoDB is case-sensitive; query fails |
| Special Characters | Set names beginning with $ are reserved words |
| No schema documentation | Cannot distinguish between field types with the same name (is "price" a Number or a String?) |
(2) MongoDB + A Solution Using Naming Conventions
Establish naming conventions + schema validation.
// === Naming Conventions(Hump-style + Business Prefix)===
// ❌ Counterexample
db.Products // Uppercase without a prefix
db["shop-db.product"] // contains . and -
db.$reserved // $ Leading reserved word
// ✅ Correct Example
db.shop_products // Business Prefix + Business Name(Lowercase and underlined)
db.shop_orders
db.shop_users
// === Schema Verification(mongoose Centralized Management of Field Types)===
const ProductSchema = new mongoose.Schema({
sku: { type: String, required: true }, // Clarify String Type
price: { type: mongoose.Schema.Types.Decimal128, required: true }, // Clarify Decimal128
createdAt: { type: Date, default: Date.now } // Clarify Date Type
});
(3) Revenue
| Dimension | Inconsistent Naming | Standard Naming |
|---|---|---|
| Discoverability | ❌ Hard to find | ✅ Easy to locate |
| Maintenance Costs | High | Low |
| Team Collaboration | High communication costs | Unambiguous |
| Backup/Restore | Prone to errors | Automated and reliable |
3. Database Concepts
Concept Explanation: A database is the top-level namespace in MongoDB, used to organize related collections. Each MongoDB instance can contain multiple databases, and each database has its own file storage, permission controls, and index space. Databases are physically isolated from one another, but $lookup join queries cannot be executed across databases.
How It Works: MongoDB allocates a separate file space for each database (one folder per database under the WiredTiger engine). Databases are not physically created—when you run use shopdb, MongoDB simply switches contexts; the database is not actually created until data is written to it for the first time. Deleting a database physically deletes the corresponding file space.
graph TB
A[MongoDB Server Examples] --> B[admin Database<br/>System Administration]
A --> C[config Database<br/>Sharded Cluster Metadata]
A --> D[local Database<br/>Dungeon Collection Status]
A --> E[shopdb Business Database]
A --> F[analyticsdb Analytical Database]
E --> E1[users Gathering]
E --> E2[products Gathering]
E --> E3[orders Gathering]
F --> F1[events Gathering]
F --> F2[user_behavior Gathering]
style E fill:#d4edda
| System Database | Purpose | Visible to Users | Writable |
|---|---|---|---|
| admin | System administration, user authentication | ✅ | ⚠️ Administrative operations only |
| config | Sharded cluster configuration | ✅ (read-only) | ❌ |
| local | Replica set status, local data | ✅ (independent per node) | ⚠️ |
| test | Test Purpose (Created by Default) | ✅ | ✅ |
(1) What is a database?
A database is the top-level namespace in MongoDB, used to organize related collections.
graph TB
A[MongoDB Server Examples] --> B[admin Database<br/>System Administration]
A --> C[config Database<br/>Sharded Cluster Metadata]
A --> D[local Database<br/>Dungeon Collection Status]
A --> E[shopdb Business Database]
A --> F[analyticsdb Analytical Database]
E --> E1[users Gathering]
E --> E2[products Gathering]
E --> E3[orders Gathering]
F --> F1[events Gathering]
F --> F2[user_behavior Gathering]
style E fill:#d4edda
(2) 4 system databases
Key Points Analysis:
adminis a very special database—users created in the admin section have global privileges.configMetadata for the storage shard cluster (almost empty in non-sharded environments)- Data from
localis not replicated to other nodes in the replica set—this is suitable for storing data that only needs to be available locally. testis the default database for mongosh; its use should be avoided in production environments.
(3) Database Naming Conventions
// === MongoDB Database Naming Conventions ===
// ✅ Valid database names
use shopdb // Alphanumeric
use shop_db // Underline
use "shop-db" // Contains a hyphen(Quotation marks are required)
use "shop.2026" // Including periods(Quotation marks are required)
// ❌ Invalid database name
use "" // Empty string
use "shop/db" // Contains a slash
use "shop$db" // $ Introduction(Although it is legal, it is not recommended)
use "admin" // System-Reserved(Although it is available, it is not recommended)
| Rule | Description |
|---|---|
| Cannot be empty | Must contain at least 1 character |
| Cannot contain | / \ . " $ * < > : | ? (Windows file system restriction) |
| Case-sensitive | shopdb ≠ SHOPDB |
| Length Limit | 64 characters (Linux filesystem limit) |
| UTF-8 | Supports Chinese (but not recommended) |
▶ Example 1: Database Management Commands
// === List all databases ===
show dbs
// admin 0.000GB
// config 0.000GB
// local 0.000GB
// shopdb 0.005GB
// test 0.000GB
// === Switch Databases ===
use shopdb
// switched to db shopdb
// === Display the current database ===
db
// shopdb
// === Delete the database(Use with caution!)===
db.dropDatabase()
// { "dropped" : "shopdb", "ok" : 1 }
// === View Database Statistics ===
db.stats()
// {
// db: 'shopdb',
// collections: 5,
// views: 0,
// objects: 1250,
// avgObjSize: 245,
// dataSize: 306250,
// storageSize: 286720,
// indexes: 8,
// indexSize: 57344,
// fileSize: 67108864,
// nsSizeMB: 16
// }
4. The Concept of Collections
Concept Explanation: A collection is a container for documents in MongoDB, similar to a "table" in a relational database, but with one fundamental difference—collections are schema-less, meaning documents within the same collection can have different combinations of fields. This flexibility is a core strength of MongoDB, but it also poses a potential risk (requiring the application layer or schema validation to ensure data quality).
How It Works: Collections are identified in the MongoDB namespace as <database>.<collection>. Collections do not store data themselves—data is stored as BSON documents in the collection’s file space, while the collection maintains only metadata (index information, schema validation rules, capped settings, etc.). A collection is created implicitly when the first document is inserted, or it can be created explicitly using createCollection().
graph TB
A[shopdb Database] --> B[users Gathering]
A --> C[products Gathering]
A --> D[orders Gathering]
B --> B1[Document 1<br/>name: Alice<br/>age: 28]
B --> B2[Document 2<br/>name: Bob<br/>age: 32<br/>role: admin]
B --> B3[Document 3<br/>name: Charlie<br/>email: c@example.com]
style B2 fill:#f8d7da
Key Points: A single collection can have different fields (schema-less); Document 1 has an age field, while Document 3 has an email field but no age field. This demonstrates MongoDB’s flexibility—but it also means that you need to use Mongoose Schema or Schema Validation to constrain the fields.
| Dimension | Relational Table | MongoDB Collection |
|---|---|---|
| Schema | Strongly constrained (defined by DDL) | Unconstrained (schema-less) |
| Field | Fields must be the same in every row | Fields may vary from row to row |
| Data Type | Strongly typed (defined by DDL) | Weakly typed (checked at runtime) |
| Relationship | Foreign Key Constraint | Application-Level Reference |
| JOIN | Native support | $lookup (limited support) |
| Horizontal Scaling | Complex | Built-in Sharding |
(1) What is a set?
A collection is a container for documents in MongoDB, similar to a "table" in a relational database, but without schema constraints.
graph TB
A[shopdb Database] --> B[users Gathering]
A --> C[products Gathering]
A --> D[orders Gathering]
B --> B1[Document 1<br/>name: Alice<br/>age: 28]
B --> B2[Document 2<br/>name: Bob<br/>age: 32<br/>role: admin]
B --> B3[Document 3<br/>name: Charlie<br/>email: c@example.com]
style B2 fill:#f8d7da
Note: A single collection can have different fields (schema-less); Document 1 has an "age" field, while Document 3 has an "email" field but no "age" field.
(2) Sets vs. Relational Tables
| Dimension | Relational Table | MongoDB Collection |
|---|---|---|
| Schema | Strongly constrained (defined by DDL) | Unconstrained (schema-less) |
| Field | Fields must be the same in every row | Fields may vary from row to row |
| Data Type | Strongly typed (defined by DDL) | Weakly typed (checked at runtime) |
| Relationship | Foreign Key Constraint | Application-Level Reference |
| JOIN | Native support | $lookup (limited support) |
| Horizontal Scaling | Complexity | Built-in Sharding |
(3) Rules for Naming Sets
// ✅ Valid collection names
db.shop_products // Alphanumeric and underscores
db["shop-products"] // Contains a hyphen(Quotation marks are required)
db.shop2026 // Contains numbers
db["shop.products"] // Including periods(Quotation marks are required)
// ❌ Invalid set names
db[""] // Empty string
db.$reserved // $ Introduction(Retain)
db["system.users"] // system. Introduction(System-Reserved)
db["shop\\products"] // Contains a backslash
▶ Example 2: Collection Management Commands
// === List all collections in the current database ===
show collections
// users
// products
// orders
// reviews
// === Explicitly Creating Sets ===
db.createCollection("users");
// { ok: 1 }
// === Implicit Collection Creation(Created automatically when inserted into a document)===
db.users.insertOne({ name: "Alice" });
// Automatically create the collection if it does not exist
// === Create a Fixed-Size Set(capped collection)===
db.createCollection("logs", {
capped: true,
size: 10485760, // 10 MB
max: 10000 // At most 10000 Documents
});
// { ok: 1 }
// === Delete Set ===
db.users.drop();
// true
// === View Collection Statistics ===
db.users.stats();
// {
// ns: 'shopdb.users',
// size: 1024,
// count: 50,
// avgObjSize: 20,
// storageSize: 8192,
// capped: false,
// max: null,
// ...
// }
5. Implicit Creation vs. Explicit Creation
Concept Explanation: MongoDB supports two methods for creating collections—implicit creation (automatically created when inserting documents) and explicit creation (manually created using createCollection()). These two methods differ significantly in terms of development experience and data security. Implicit creation is recommended during the development phase (for rapid iteration), while explicit creation combined with schema validation is recommended for production environments (to prevent dirty data).
How It Works: With implicit creation, MongoDB automatically creates the database and collection during the first write operation, using default settings (no capped collection, no validation rules). With explicit creation, you can specify schema validation rules, capped collection settings, sorting rules, and more in advance to ensure that subsequent writes comply with business constraints.
| Dimension | Implicit Creation | Explicit Creation |
|---|---|---|
| Syntax | insertOne() Auto-create |
createCollection() |
| Schema Validation | ❌ None | ✅ JSON Schema can be defined |
| Capped setting | ❌ Default: not capped | ✅ Can be specified |
| Use Cases | Development, Testing | Production, Rigorous Data Validation |
| Spelling errors | Prone to errors | Must be specified manually |
(1) Implicit Creation (Recommended for Development)
// 1. Switch Databases(If it doesn't exist, create it later)
use shopdb;
// 2. Insert directly into the document
db.users.insertOne({ name: "Alice" });
// Automatically Create users Gathering
// 3. View Automatically Created Collections
show collections;
// users
Advantages: Simple and fast; no manual management required
Disadvantages: May accidentally create sets with spelling errors (e.g., user vs. users)
(2) Explicit Creation (Recommended for Production Use)
// 1. Create an empty set(For predefined structures)
db.createCollection("users");
db.createCollection("products");
db.createCollection("orders");
// 2. Create a collection with validation(Schema Validation)
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["email", "username"],
properties: {
email: {
bsonType: "string",
pattern: "^.+@.+$"
},
username: {
bsonType: "string",
minLength: 3,
maxLength: 30
},
age: {
bsonType: "int",
minimum: 0,
maximum: 150
}
}
}
},
validationLevel: "strict",
validationAction: "error"
});
(3) Comparison of the Two Methods
| Dimension | Implicit Creation | Explicit Creation |
|---|---|---|
| Syntax | insertOne() Auto-create |
createCollection() |
| Schema Validation | ❌ None | ✅ JSON Schema can be defined |
| Capped setting | ❌ Default: not capped | ✅ Can be specified |
| Use Cases | Development, Testing | Production, Rigorous Data Validation |
| Spelling errors | Prone to errors | Must be specified manually |
▶ Example 3: Capped Collection
// === Create capped collection(Circular Queue)===
db.createCollection("activity_logs", {
capped: true,
size: 10485760, // 10 MB Upper Limit
max: 100000 // At most 100,000 Documents
});
// === Insert Document(Once it's full, it will automatically overwrite the oldest entries.)===
for (let i = 0; i < 5; i++) {
db.activity_logs.insertOne({
userId: `user_${i}`,
action: "login",
timestamp: new Date()
});
}
// === Search ===
db.activity_logs.find().sort({ timestamp: -1 }).limit(5);
// === Edit capped collection size ===
db.runCommand({
collMod: "activity_logs",
cappedSize: 20971520 // Expand to 20 MB
});
// === Convert to a regular collection(Irreversible!)===
db.runCommand({
collMod: "activity_logs",
cappedSize: -1
});
Capped Collection Use Cases:
- Logging system (automatically clears old logs)
- Message queue (retains the most recent N messages)
- Real-time data streams (stock prices, sensor data)
Situations Where This Is Not Appropriate:
- Documentation needs to be updated (capped does not support in-place updates that exceed the original size)
- Need to delete specific documents (capped does not allow selective deletion)
6. Collection Namespaces
Concept Explanation: A namespace is MongoDB’s internal method for uniquely identifying collections, and it follows the format <database>.<collection>. For example, shopdb.users refers to the users collection in the shopdb database. Namespaces are used by MongoDB’s storage engine to locate data and index files; understanding namespaces helps in understanding MongoDB’s internal storage structure.
How It Works: The WiredTiger storage engine creates separate data and index files for each collection, with filenames that include a hash of the namespace. The namespace file (.ns file) stores metadata for all collections (index information, validation rules, capped settings, etc.). The namespace file is 16 MB by default, which limits the number of collections that can be created in each database.
graph TB
A[MongoDB Namespace] --> B[Database Name.Set Name]
B --> C[shopdb.users]
B --> D[shopdb.products]
B --> E[shopdb.orders]
B --> F[analytics.events]
style A fill:#cce5ff
| Item | Restriction | Description |
|---|---|---|
| Namespace File Size | Default: 16 MB | Can be adjusted via --nssize |
| Number of Sets/Database | Determined by the namespace file size | Approximately 24,000 (at 16 MB) |
| Total namespace length | ≤ 120 bytes | Database name + "." + collection name |
(1) Namespace Structure
graph TB
A[MongoDB Namespace] --> B[Database Name.Set Name]
B --> C[shopdb.users]
B --> D[shopdb.products]
B --> E[shopdb.orders]
B --> F[analytics.events]
style A fill:#cce5ff
Namespace = <database>.<collection>; MongoDB uses the .ns file to store metadata internally.
(2) Namespace Size Limit
| Item | Restriction |
|---|---|
| Namespace File Size | Default 16 MB |
| Number of sets/database | Determined by the namespace file size |
| Adjusting Namespace Size | Requires restarting mongod |
(3) View all namespaces
// === View the namespaces for all collections ===
db.getCollectionNames();
// [ 'users', 'products', 'orders', 'reviews', 'activity_logs' ]
// === Namespaces with prefixes ===
db.getCollectionInfos();
// [
// { name: 'users', type: 'collection' },
// { name: 'products', type: 'collection' },
// ...
// ]
// === View the namespace of the collection(ns) ===
db.users.stats().ns;
// 'shopdb.users'
// === Switch Sets(For long set names)===
const productsCollection = db.getCollection("products");
productsCollection.findOne();
// equivalent to db.products.findOne();
7. Collection Metadata Management
(1) Set Statistics
// === Statistics for a Single Set ===
db.users.stats();
// {
// ns: 'shopdb.users', // Namespace
// size: 10240, // Data Size(Byte)
// count: 250, // Number of documents
// avgObjSize: 40, // Average Document Size
// storageSize: 12288, // Disk Usage
// capped: false, // Is it a fixed set?
// max: null, // Maximum number of documents(capped)
// maxSize: null, // Maximum size(capped)
// totalIndexSize: 16384, // Total Index Size
// indexSizes: { // Index Sizes
// _id_: 8192,
// email_1: 4096
// }
// }
// === Index Information for Sets ===
db.users.getIndexes();
// [
// { v: 2, key: { _id: 1 }, name: '_id_' },
// { v: 2, key: { email: 1 }, name: 'email_1', unique: true }
// ]
// === Aggregate Data Size(Does not include indexes)===
db.users.dataSize();
// 10240
(2) Storing Information in Sets
// === View the collection's WiredTiger Store Information ===
db.users.storageSize();
// 12288
// === View all namespace information for the collection ===
db.users.totalSize();
// 24576
// === Index size within the set ===
db.users.totalIndexSize();
// 16384
▶ Example 4: Collection Health Check Script
// === Group Physical Exams ===
function checkCollectionHealth(collName) {
const stats = db[collName].stats();
const indexes = db[collName].getIndexes();
print(`\n=== ${collName} Health Report ===`);
print(`Number of documents: ${stats.count}`);
print(`Data Size: ${(stats.size / 1024).toFixed(2)} KB`);
print(`Average Document Size: ${stats.avgObjSize} bytes`);
print(`Disk Usage: ${(stats.storageSize / 1024).toFixed(2)} KB`);
print(`Number of Indexes: ${indexes.length}`);
print(`Index Size: ${(stats.totalIndexSize / 1024).toFixed(2)} KB`);
print(`Data/Disk Ratio: ${((stats.size / stats.storageSize) * 100).toFixed(1)}%`);
print(`Is it capped: ${stats.capped ? 'Yes' : 'No'}`);
if (stats.capped) {
print(`capped size: ${(stats.maxSize / 1024 / 1024).toFixed(2)} MB`);
print(`capped max docs: ${stats.max}`);
}
}
// Check all sets
db.getCollectionNames().forEach(checkCollectionHealth);
8. Best Practices for Databases and Collections
(1) Database Design Principles
graph TB
A[Database Partitioning] --> B[By Business Domain<br/>shopdb / analyticsdb / logdb]
A --> C[By Environment<br/>shopdb_dev / shopdb_staging / shopdb_prod]
A --> D[By Tenant<br/>shopdb_tenant1 / shopdb_tenant2]
B --> B1[✅ Recommendations]
C --> C2[⚠️ Small and Medium-Sized Projects]
D --> D3[⚠️ SaaS Multi-tenant]
(2) Principles of Set Design
| Principle | Description |
|---|---|
| Lowercase + underscore | shop_orders rather than ShopOrders |
| Service Prefix | shop_, blog_, crm_ (to avoid conflicts) |
| Avoid reserved words | Do not use names starting with system. or $ |
| Length Limit | Collection name ≤ 120 characters (including index prefixes) |
| Singular vs. Plural | Plural recommended (orders rather than order) |
(3) Control of the Number of Sets
| Database | Number of Recommended Sets | Reason |
|---|---|---|
| Small Projects | 5–20 | Simple and Clear |
| Medium-sized projects | 20–100 | Business expansion |
| Large Projects | 100–500 | Note: Namespace Limits |
| Ultra-large projects | > 500 | Consider splitting across multiple databases |
▶ Example 5: Database Structure for an E-commerce Project
// === shopdb Database Structure ===
shopdb/
├── users // User Information
├── user_addresses // Shipping Address(If you need to be independent)
├── products // Products
├── product_variants // Product Variants(Color/Dimensions)
├── categories // Product Categories
├── orders // Order
├── order_items // Order Items(If the data volume is large)
├── reviews // Product Reviews
├── carts // Shopping Cart
├── coupons // Coupon
├── sessions // User Session
└── activity_logs // User Behavior Logs(capped collection)
// === analyticsdb Database Structure(Data Analysis)===
analyticsdb/
├── user_events // User Events
├── page_views // Page Views
├── conversion_data // Conversion Funnel
└── aggregated_stats // Aggregate Statistics
// === logdb Database Structure(Operations Logs)===
logdb/
├── app_logs // App Logs(capped)
├── error_logs // Error Log
└── audit_logs // Audit Log
9. Comprehensive Hands-On Exercise: Initializing an E-commerce Platform Database
(1) Scenario Requirements
Set up a MongoDB database for an e-commerce platform, including:
- Core Business Entities (users/products/orders/reviews)
- Log Collection (capped collection)
- Database Initialization Script
(2) Initialization Script
// === init-shopdb.js ===
// 1. Create a Database(Implicit)
const dbName = 'shopdb';
use(dbName);
// 2. Explicitly Creating a Core Collection(with Schema Validation)
db.createCollection('users', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['email', 'username'],
properties: {
email: {
bsonType: 'string',
pattern: '^.+@.+$'
},
username: {
bsonType: 'string',
minLength: 3,
maxLength: 30
},
role: {
enum: ['customer', 'admin', 'moderator']
}
}
}
}
});
db.createCollection('products', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['sku', 'title', 'price'],
properties: {
sku: {
bsonType: 'string',
pattern: '^[A-Z0-9-]+$'
},
price: {
bsonType: 'decimal'
}
}
}
}
});
// 3. Create a Regular Set
db.createCollection('orders');
db.createCollection('reviews');
db.createCollection('carts');
// 4. Create capped collection(Log)
db.createCollection('activity_logs', {
capped: true,
size: 10485760, // 10 MB
max: 100000 // At most 10 10,000 entries
});
// 5. Create an Index
db.users.createIndex({ email: 1 }, { unique: true });
db.users.createIndex({ username: 1 }, { unique: true });
db.users.createIndex({ createdAt: -1 });
db.products.createIndex({ sku: 1 }, { unique: true });
db.products.createIndex({ category: 1, price: 1 });
db.products.createIndex({ title: 'text', description: 'text' });
db.orders.createIndex({ userId: 1, createdAt: -1 });
db.orders.createIndex({ status: 1 });
db.reviews.createIndex({ productId: 1, createdAt: -1 });
db.reviews.createIndex({ userId: 1 });
// 6. Verification Initialization
print('=== shopdb Initialization Complete ===');
print(`Number of sets: ${db.getCollectionNames().length}`);
db.getCollectionNames().forEach(name => {
print(` - ${name}`);
});
// 7. Perform Initialization
mongosh "mongodb://localhost:27017" init-shopdb.js
(3) Verify the database structure
// === View the database structure ===
db.adminCommand('listCollections', { db: 'shopdb' });
// {
// cursor: {
// firstBatch: [
// { name: 'users', type: 'collection', info: { ... } },
// { name: 'products', type: 'collection', info: { ... } },
// ...
// ]
// }
// }
// === View Collection Statistics ===
db.getCollectionNames().forEach(name => {
const stats = db[name].stats();
print(`${name}: ${stats.count} docs, ${(stats.size / 1024).toFixed(2)} KB`);
});
❓ FAQ
user vs. users would create two collections). In production environments, we recommend explicit creation combined with schema validation to avoid dirty data.$lookup is limited to sets within the same database. Cross-database JOINs require multiple queries at the application layer or the use of Atlas Data Lake.db.collection.findOne() verify before deleting in a production environment.📖 Summary
- A database is a namespace for collections, and a collection is a container for documents
- MongoDB has four default system databases: admin, config, local, and test
- Sets are schema-less; a single set can have different fields.
- Naming convention: lowercase letters + underscore + business prefix; avoid special characters
- Implicit creation is simple but prone to typos; explicit creation is safe but cumbersome.
- A capped collection is a fixed-size circular queue, suitable for logging and message queues.
- Aggregate statistics:
db.collection.stats(),getIndexes(),dataSize()
📝 Exercises
-
Basic Question (⭐): Create a database named
shopdbin Mongosh that contains three collections:users,products, andorders. List all databases and collections. -
Basic Question (⭐): Use
db.users.insertOne({...})to implicitly create a new collection (such as "sessions") and understand MongoDB's implicit creation mechanism. -
Advanced Exercise (⭐⭐): Create a capped collection
activity_logs(size 5MB, max 1000), insert 100 documents, and verify that the oldest documents are automatically overwritten. -
Advanced Exercise (⭐⭐): Write an init script
init-shopdb.jsto create the users/products/orders collection (with schema validation), create at least 5 indexes, and create a capped collection for logs. -
Advanced Exercise (⭐⭐): Use
db.collection.stats()to inspect all collections, and write a script that outputs a tabular report containing the "collection name, number of documents, data size, average document size, and number of indexes." -
Challenge (⭐⭐⭐): Design a SaaS multi-tenant database schema (split into 5 databases by business domain), write a complete init script to create all collections, indexes, and schema validation, and output an initialization report.



