Working with MongoDB Views

1. Creating Views

FormEffect
db.createView("activeUsers", "users", [pipeline])Read-only view
MaterializationComputed on read (lazy)

2. Querying Views

AspectDetail
find/aggregateSupported (read-only)
IndexesUnderlying collection indexes used
No write opsinsert/update/delete rejected

3. Using Aggregation Pipelines in Views

AllowedDisallowed
$match, $project, $group, $lookup$out, $merge
$facet$indexStats

4. Dropping Views

FormNotes
db.activeUsers.drop()Same syntax as collection

5. Listing Views

MethodDetail
db.getCollectionInfos({type: "view"})Filter view types
system.viewsInternal storage of view definitions

6. Understanding View Limitations

LimitDetail
Read-onlyNo writes
No text indexCannot use $text on view
No $geoNearUse underlying collection
Find limitationsFind on view cannot use $natural sort or special options

7. Modifying View Definition

CommandEffect
collMod with viewOn / pipelineReplace definition atomically

8. Using Views for Security

PatternDetail
Hide PIIProject out sensitive fields
Per-tenant filter$match on tenantId
Role grantsGrant read on view; deny on underlying coll

9. Materializing View Results

MethodDetail
$merge or $out in pipelineWrite to physical collection
Refresh scheduleCron / change-stream-driven

10. Creating On-Demand Materialized Views

AspectDetail
PipelineEnds in $merge into target collection
IncrementalFilter by lastUpdated > cutoff
Use casePre-aggregated dashboards
db.sales.aggregate([
  { $match: { date: { $gte: lastRun } } },
  { $group: { _id: { $dateTrunc: { date: "$date", unit: "day" } }, total: { $sum: "$amount" } } },
  { $merge: { into: "dailySales", whenMatched: "merge", whenNotMatched: "insert" } }
]);