MongoDB Document Modeling
MongoDB Document Modeling: Tips & Tricks
MongoDB Document Modeling: Tips & Tricks
Tip: Embed When Accessed Together
If you always read comments with the post, embed them:
$post->comments = [
['user_id' => 1, 'body' => 'Great!', 'created_at' => now()],
];
Gotcha: 16MB Document Limit
A single MongoDB document can't exceed 16MB. If comments can grow unbounded, reference them instead.
Tip: Reference for Many-to-Many
class Post extends Model
{
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
}
Tags are shared across posts — use references.
Gotcha: Embedding Makes Updates Harder
Updating a deeply nested field requires dot notation:
Post::where('_id', $id)->update(['comments.0.body' => 'New text']);
Tip: Denormalize for Read Performance
Store author_name in the post document to avoid joining:
Post::create([
'title' => 'Hello',
'author_id' => $user->id,
'author_name' => $user->name, // Denormalized
]);
Gotcha: Array Order Matters
MongoDB preserves array order. Use $push with $sort to maintain order.
Tip: Schema Validation for Safety
DB::command([
'collMod' => 'posts',
'validator' => [
'$jsonSchema' => [
'bsonType' => 'object',
'required' => ['title', 'content'],
'properties' => [
'title' => ['bsonType' => 'string'],
],
],
],
]);
Gotcha: Embedding vs Referencing Decision
- Embed: one-to-few, always accessed together
- Reference: many-to-many, unbounded growth, shared data
Tip: Embed or Reference? The 80/20 Rule
If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.
Tip: Index Your Query Patterns, Not All Fields
Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.
Gotcha: No Transaction Rollback for Index Builds
Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.
Senior Insight
MongoDB's schema flexibility is both its greatest strength and its most dangerous pitfall. I've seen databases where the same collection had documents with completely different structures because developers treated 'schema-less' as 'schema-not-needed'. The discipline of schema design is even more important in MongoDB than in relational databases because there's no schema enforcement by default. Document your schema, validate it with $jsonSchema, and enforce it in your application layer.
Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)