A MongoDB view is a queryable, read-only result defined by an aggregation pipeline over a collection or another view. Its contents are not stored on disk; MongoDB generates them from the underlying data when a client queries the view. section 2.6.3
Use a view to expose selected fields, simplify a complex data structure, reuse aggregation logic, or combine information without physically merging collections. A standard view calculates its result at read time. An on-demand materialized view instead stores a precalculated result on disk to improve read performance. section 2.6.3 section 2.7
Listing 2.6 Creating a MongoDB view
use sample_training
db.createView(
"aerocondorRoutesView", // Name of the view
"routes", // Source collection
[
{
$match: { "airline.id": 410 } // Filter to include only routes
operated by Aerocondor
}
]
)
Create a filtered view with db.createView(): name the view, identify its source collection, then supply a pipeline. Here, $match limits routes to those whose airline.id is 410. section 2.6.3
Enrich transactions for reading
In sample_analytics, a view over transactions uses $lookup to match customers by account ID. A $set stage selects fields from the matching customer, and $unset removes the temporary lookup array. Query the resulting view with db.enriched_transactions.find().limit(5). section 6.2.1
Create the view in the same database as its source collection. Do not put $out or $merge in the view-definition pipeline, including pipelines embedded in stages such as $lookup or $facet. section 6.2.1




