Docs Menu
Docs Home
/
MongoDB Manual
/ / /

Create and Query a View

On this page

  • db.createCollection() Syntax
  • db.createView() Syntax
  • Restrictions
  • Unsupported Operations
  • Example
  • Populate the Collection
  • Use db.createView() to Create a View
  • Use db.createCollection() to Create a View
  • Behavior
  • Aggregation Optimizations
  • Resource Locking

To create a view, use one of the following methods:

To create a view in the MongoDB Atlas UI, you must use a materialized view. To learn more, see Create a Materialized View in the MongoDB Atlas UI.

Important

View Names are Included in Collection List Output

Operations that list collections, such as db.getCollectionInfos() and db.getCollectionNames(), include views in their outputs.

The view definition is public; i.e. db.getCollectionInfos() and explain operations on the view will include the pipeline that defines the view. As such, avoid referring directly to sensitive fields and values in view definitions.

db.createCollection(
"<viewName>",
{
"viewOn" : "<source>",
"pipeline" : [<pipeline>],
"collation" : { <collation> }
}
)
db.createView(
"<viewName>",
"<source>",
[<pipeline>],
{
"collation" : { <collation> }
}
)
  • You must create views in the same database as the source collection.

  • A view definition pipeline cannot include the $out or the $merge stage. This restriction also applies to embedded pipelines, such as pipelines used in $lookup or $facet stages.

  • You cannot rename a view once it is created.

Some operations are not available with views:

For more information, see Supported Operations for Views.

This example populates a collection with student data and creates a view to query the data.

Create a students collection to use for this example:

db.students.insertMany( [
{ sID: 22001, name: "Alex", year: 1, score: 4.0 },
{ sID: 21001, name: "bernie", year: 2, score: 3.7 },
{ sID: 20010, name: "Chris", year: 3, score: 2.5 },
{ sID: 22021, name: "Drew", year: 1, score: 3.2 },
{ sID: 17301, name: "harley", year: 6, score: 3.1 },
{ sID: 21022, name: "Farmer", year: 1, score: 2.2 },
{ sID: 20020, name: "george", year: 3, score: 2.8 },
{ sID: 18020, name: "Harley", year: 5, score: 2.8 },
] )

Use db.createView() to create a view that is limited to first year students:

db.createView(
"firstYears",
"students",
[ { $match: { year: 1 } } ]
)

In the example:

  • firstYears is the name of the new view.

  • students is the collection the view is based on.

  • $match is an aggregation expression that matches first year students in the students collection.

This example queries the view:

db.firstYears.find({}, { _id: 0 } )

The following output only contains the documents with data on first year students. The { _id: 0 } projection suppresses the _id field in the output.

[
{ sID: 22001, name: 'Alex', year: 1, score: 4 },
{ sID: 22021, name: 'Drew', year: 1, score: 3.2 },
{ sID: 21022, name: 'Farmer', year: 1, score: 2.2 }
]

Note

Projection Restrictions

find() operations on views do not support the following projection operators:

The db.createCollection() method allows you to create a collection or a view with specific options.

The following example creates a graduateStudents view. The view only contains documents selected by the $match stage. The optional collation setting determines the sort order.

db.createCollection(
"graduateStudents",
{
viewOn: "students",
pipeline: [ { $match: { $expr: { $gt: [ "$year", 4 ] } } } ],
collation: { locale: "en", caseFirst: "upper" }
}
)

Note

Collation Behavior

  • You can specify a default collation for a view at creation time. If no collation is specified, the view's default collation is the "simple" binary comparison collator. That is, the view does not inherit the collection's default collation.

  • String comparisons on the view use the view's default collation. An operation that attempts to change or override a view's default collation will fail with an error.

  • If creating a view from another view, you cannot specify a collation that differs from the source view's collation.

  • If performing an aggregation that involves multiple views, such as with $lookup or $graphLookup, the views must have the same collation.

The following example queries the view. The $unset stage removes the _id field from the output for clarity.

db.graduateStudents.aggregate(
[
{ $sort: { name: 1 } },
{ $unset: [ "_id" ] }
]
)

When the output is sorted, the $sort stage uses the collation ordering to sort uppercase letters before lowercase letters.

[
{ sID: 18020, name: 'Harley', year: 5, score: 2.8 },
{ sID: 17301, name: 'harley', year: 6, score: 3.1 }
]

The following sections describe the behaviors of view creation and queries.

When you query a view:

db.createView() obtains an exclusive lock on the specified collection or view for the duration of the operation. All subsequent operations on the collection must wait until db.createView() releases the lock. db.createView() typically holds this lock for a short time.

Creating a view requires obtaining an additional exclusive lock on the system.views collection in the database. This lock blocks creation or modification of views in the database until the command completes.

Back

Views