$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[June 14, 2025] MongoDB

MongoDB DBRef: Database References

MongoDB DBRef: Database References

────────────────────────────────────────────────────────

MongoDB DBRef: Database References

Tip: DBRef Format

[
    '$ref' => 'users',
    '$id' => new MongoDB\BSON\ObjectId('...'),
    '$db' => 'myapp',
]

Standard format for referencing documents in other collections.

Gotcha: DBRef Requires Manual Resolution

MongoDB doesn't auto-resolve DBRefs. You must query the referenced collection manually.

Tip: Manual References Are Simpler

['author_id' => new MongoDB\BSON\ObjectId('...')]

Most applications use manual references instead of DBRef.

Gotcha: DBRef and Indexing

DBRef fields can be indexed like any other field. Index $id for fast lookups.

Tip: Cross-Database References

DBRef includes the $db field for cross-database references. Manual references don't support this.

Gotcha: DBRef in Aggregation

Use $lookup to resolve DBRefs in aggregation pipelines.

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

Document modeling in MongoDB is where experience makes the difference. The 80/20 rule I use: if you always access data together, embed it. If you access it independently, reference it. But the 16MB document limit is your hard boundary — I stay under 1MB for most documents to leave room for growth. The most common antipattern I see: embedding arrays that grow unboundedly. A user's comments array that starts at 10KB and grows to 10MB will eventually hit the limit.

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/)

────────────────────────────────────────────────────────
<-- back to posts