Implementing Document Databases

1. Storing JSON Documents

DBFormat
MongoDBBSON (binary JSON)
CouchbaseJSON
PGJSONB
DynamoDBJSON-like with type tags
FirestoreDocument 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

IndexUse
Single fieldEquality / range
CompoundMulti-field — order matters (ESR rule)
MultikeyOn array fields
TextFull-text search
Geospatial2dsphere
PartialFilter expression for sparse indexing
TTLAuto-expire docs
WildcardIndex 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

StrategyDetail
schema_version fieldMigration on read or batch
__v / version counterOptimistic concurrency
History collectionSnapshot prior versions
Change streamsReact to all changes

6. Implementing Atomic Updates

OperatorUse
$set / $unsetUpdate / remove field
$incAtomic increment
$push / $pull / $addToSetArray ops
findAndModifyAtomic read-modify-write
Transactions (4.0+)Multi-document atomicity

7. Designing Sub-Document Structures

PatternDetail
Embed for 1:fewCo-locate child data
Object map vs arrayUse map keyed by id for fast updates
Bucket for time-seriesCap array size per doc
Avoid deep nestingKeep ≤ 3 levels for query clarity

8. Handling Array Fields

ConcernDetail
Unbounded growthUse subset pattern
Positional ops$, $[], $[<identifier>]
Multikey index limitsOne array per compound index
OrderingMaintain explicitly or via $push $sort
ToolDetail
MongoDB Atlas SearchLucene-backed
text indexBasic in-engine search
External (Elasticsearch)Sync via change streams
PG tsvectorFor JSONB documents in Postgres

10. Optimizing Document Storage

TipDetail
Short field namesRepeats per doc — savings add up
WiredTiger compressionSnappy default; zstd higher ratio
Right doc sizeAvoid massive 10+ MB docs
Index hygieneDrop unused indexes (cost on writes)
Pre-allocationLess relevant on WiredTiger