Implementing Document Databases
1. Storing JSON Documents
| DB | Format |
|---|---|
| MongoDB | BSON (binary JSON) |
| Couchbase | JSON |
| PG | JSONB |
| DynamoDB | JSON-like with type tags |
| Firestore | Document fields with types |
2. Creating and Updating Documents
Example: MongoDB Insert & Update
db.users.insertOne({
_id: ObjectId(), name: "Ada", email: "ada@x.com",
addresses: [{type: "home", city: "London"}],
created_at: new Date()
});
db.users.updateOne(
{ _id: id },
{ $set: { "addresses.0.city": "Oxford" }, $inc: { version: 1 } }
);
3. Indexing Document Fields
| Index | Use |
|---|---|
| Single field | Equality / range |
| Compound | Multi-field — order matters (ESR rule) |
| Multikey | On array fields |
| Text | Full-text search |
| Geospatial | 2dsphere |
| Partial | Filter expression for sparse indexing |
| TTL | Auto-expire docs |
| Wildcard | Index any field path |
4. Implementing Document Validation
Example: $jsonSchema Validator
db.createCollection("orders", {
validator: { $jsonSchema: {
bsonType: "object",
required: ["customer_id","total","status"],
properties: {
total: { bsonType: "decimal", minimum: 0 },
status: { enum: ["pending","paid","shipped","cancelled"] }
}
} },
validationLevel: "strict",
validationAction: "error"
});
5. Managing Document Versioning
| Strategy | Detail |
|---|---|
| schema_version field | Migration on read or batch |
| __v / version counter | Optimistic concurrency |
| History collection | Snapshot prior versions |
| Change streams | React to all changes |
6. Implementing Atomic Updates
| Operator | Use |
|---|---|
| $set / $unset | Update / remove field |
| $inc | Atomic increment |
| $push / $pull / $addToSet | Array ops |
| findAndModify | Atomic read-modify-write |
| Transactions (4.0+) | Multi-document atomicity |
7. Designing Sub-Document Structures
| Pattern | Detail |
|---|---|
| Embed for 1:few | Co-locate child data |
| Object map vs array | Use map keyed by id for fast updates |
| Bucket for time-series | Cap array size per doc |
| Avoid deep nesting | Keep ≤ 3 levels for query clarity |
8. Handling Array Fields
| Concern | Detail |
|---|---|
| Unbounded growth | Use subset pattern |
| Positional ops | $, $[], $[<identifier>] |
| Multikey index limits | One array per compound index |
| Ordering | Maintain explicitly or via $push $sort |
9. Implementing Full-Text Search
| Tool | Detail |
|---|---|
| MongoDB Atlas Search | Lucene-backed |
| text index | Basic in-engine search |
| External (Elasticsearch) | Sync via change streams |
| PG tsvector | For JSONB documents in Postgres |
10. Optimizing Document Storage
| Tip | Detail |
|---|---|
| Short field names | Repeats per doc — savings add up |
| WiredTiger compression | Snappy default; zstd higher ratio |
| Right doc size | Avoid massive 10+ MB docs |
| Index hygiene | Drop unused indexes (cost on writes) |
| Pre-allocation | Less relevant on WiredTiger |