Working with MongoDB Views
1. Creating Views
| Form | Effect |
|---|---|
db.createView("activeUsers", "users", [pipeline]) | Read-only view |
| Materialization | Computed on read (lazy) |
2. Querying Views
| Aspect | Detail |
|---|---|
| find/aggregate | Supported (read-only) |
| Indexes | Underlying collection indexes used |
| No write ops | insert/update/delete rejected |
3. Using Aggregation Pipelines in Views
| Allowed | Disallowed |
|---|---|
| $match, $project, $group, $lookup | $out, $merge |
| $facet | $indexStats |
4. Dropping Views
| Form | Notes |
|---|---|
db.activeUsers.drop() | Same syntax as collection |
5. Listing Views
| Method | Detail |
|---|---|
| db.getCollectionInfos({type: "view"}) | Filter view types |
| system.views | Internal storage of view definitions |
6. Understanding View Limitations
| Limit | Detail |
|---|---|
| Read-only | No writes |
| No text index | Cannot use $text on view |
| No $geoNear | Use underlying collection |
| Find limitations | Find on view cannot use $natural sort or special options |
7. Modifying View Definition
| Command | Effect |
|---|---|
| collMod with viewOn / pipeline | Replace definition atomically |
8. Using Views for Security
| Pattern | Detail |
|---|---|
| Hide PII | Project out sensitive fields |
| Per-tenant filter | $match on tenantId |
| Role grants | Grant read on view; deny on underlying coll |
9. Materializing View Results
| Method | Detail |
|---|---|
| $merge or $out in pipeline | Write to physical collection |
| Refresh schedule | Cron / change-stream-driven |
10. Creating On-Demand Materialized Views
| Aspect | Detail |
|---|---|
| Pipeline | Ends in $merge into target collection |
| Incremental | Filter by lastUpdated > cutoff |
| Use case | Pre-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" } }
]);