liveBook · Manning

Db.createView()

As explained in MongoDB 8.0 in Action, Third Edition

db.createView() is the MongoDB database method that creates a named read-only view from an aggregation pipeline over a collection or view.

db.createView() creates a named read-only view from an aggregation pipeline over a collection. The view provides a concise, reusable way to expose selected data without altering the source collection. section 2.6.3

Use a view to:

  • Limit exposure of sensitive information for particular users or applications. section 2.6.3
  • Encapsulate frequently used aggregation logic behind a consistent queryable name. section 2.6.3
  • Combine information from multiple collections without physically merging their data. section 2.6.3

Create a filtered route view

use sample_training db.createView( "aerocondorRoutesView", "routes", [ { $match: { "airline.id": 410 } } ] ) Query it with db.aerocondorRoutesView.find() to retrieve routes operated by Aerocondor. section 2.6.3

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
        }
    ]
)

Inspect the complete MongoDB shell listing for creating the filtered view. section 2.6.3

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines creation with an aggregation pipeline and demonstrates one $match stage, while contrasting regular views with disk-backed materialized views.
Examples
Filters the routes collection by airline.id 410 and queries the resulting aerocondorRoutesView.
What you can do after
Build it from scratch by defining a named view, selecting its source collection, and supplying an aggregation pipeline.
How it connects
Links aggregation pipelines with collections, views, read-only access, and on-demand materialized views.

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.