Views

Views are named aggregations queried like a collection.

Create a view: a named aggregation your application queries as if it were a collection.

Requirements

  • A user with dbAdmin or readWrite on the database to create collections.

Create

JavaScript
db.createView("paidOrders", "orders", [{ $match: { status: "paid" } }, { $project: { customer: 1, total: 1 } }]);

Query

JavaScript
db.paidOrders.find({ total: { $gte: 100 } });

The view stores no data. Each query runs its pipeline on the source collection.

Check

In mongosh, db.getCollectionInfos({ name: "paidOrders" }) shows the view with type: "view" and the pipeline it runs.

Common problems

  • A write to the view fails, because views are read-only.

See also