Logical Structure
Storage Engine Comparison
| Engine | Status | Use/Notes |
|---|---|---|
| WiredTiger | Default | Cache≈50% RAM, compression, transaction support |
| MMAPv1 | Historical/no longer used | Only for background reference |
| In-Memory | Enterprise | Low latency/not persistent |
WiredTiger
- MongoDB 3.2 and later default storage engine
- Document-level concurrency control, supports multi-document transactions
- Supports compression algorithms (snappy and zlib)
- Defaults to approximately 50% of physical RAM
Data Model
Embedded Model
Store associated data within the same document structure.
Advantages:
- High query performance
- Easy data consistency guarantee
- Avoid complex join operations
Applicable Scenarios:
- Data relationships are 1:1 or 1:few
- Embedded data usually needs to be queried together with parent document
Referenced Model
Establish association relationships by storing references to other documents.
Implementation:
- Manual reference: Store _id field of target document
- DBRef reference: Use MongoDB’s DBRef standard format
Applicable Scenarios:
- Data relationships are 1:many or many:many
- Associated data needs frequent independent updates
How to Choose
Choose Embedded
- Data objects have containment relationship
- Data that needs to be read together frequently
- Has map-reduce, aggregation requirements
Choose Reference
- Embedded data would cause a lot of data duplication
- Need to express relatively complex many:many relationships
- Large hierarchical result datasets
Minimal Runnable Example
// Insert data
db.authors.insertMany([{_id:1,name:"Li Si"},{_id:2,name:"Wang Wu"}]);
db.posts.insertMany([
{_id:101,title:"MongoDB Guide", author_id:1, tags:["db","mongo"]},
{_id:102,title:"Modeling Practice", author_id:2, tags:["design"]}
]);
// Create index
db.posts.createIndex({author_id:1});
// $lookup query
db.posts.aggregate([
{$match:{tags:"db"}},
{$lookup:{from:"authors", localField:"author_id", foreignField:"_id", as:"author"}}
]);
explain() Reading Quick Reference
| Field | What to Look For | Action |
|---|---|---|
| stage | COLLSCAN vs IXSCAN | COLLSCAN appears → add index |
| nReturned / totalDocsExamined | Ratio | Ratio≪1 → rewrite query/composite index |
| indexName | Which index hit | Adjust order/composite fields |