On this page
db.createView()
On this page
db.createView( )-
New in version 3.4.
Creates a view as the result of the applying the specified aggregation pipeline to the source collection or view. Views act as read-only collections, and are computed on demand during read operations. You must create views in the same database as the source collection. MongoDB executes read operations on views as part of the underlying aggregation pipeline.
The
db.createViewhas the following syntax:db.createView(<view>, <source>, <pipeline>, <options>)The method accepts the following parameters:
Parameter Type Description viewstring The name of the view to create. sourcestring The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create. You must create views in the same database as the source collection. pipelinearray An array that consists of the aggregation pipeline stage.
db.createViewcreates the view by applying the specifiedpipelineto thesourcecollection or view.The view definition is public; i.e.
db.getCollectionInfos()andexplainoperations on the view will include the pipeline that defines the view. As such, avoid referring directly to sensitive fields and values in view definitions.optionsdocument Optional. Additional options for the method. The options document contains the following option field:
Field Type Description collationdocument Optional. Specifies the default collation for the view.
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
If the underlying
sourceis a collection, the view does not inherit the collection’s collation settings.If no collation is specified, the view’s default collation is the “simple” binary comparison collator.
If the underlying
sourceis another view, the view must specify the same collation settings.The collation option has the following syntax:
collation: { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int>, numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean> }When specifying collation, the
localefield is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.New in version 3.4.
The
db.createView()method wraps the followingcreatecommand operation:db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline>, collation: <collation> } )Operations that lists collections, such as
db.getCollectionInfos()anddb.getCollectionNames(), includes views in their outputs.Important
The view definition is public; i.e.
db.getCollectionInfos()andexplainoperations on the view will include the pipeline that defines the view. As such, avoid referring directly to sensitive fields and values in view definitions.To remove a view, use the
drop()method on the view.
Behavior
Views exhibit the following behavior:
Read Only
Views are read-only; write operations on views will error.
The following read operations can support views:
Index Use and Sort Operations
Views use the indexes of the underlying collection.
As the indexes are on the underlying collection, you cannot create, drop or re-build indexes on the view directly nor get a list of indexes on the view.
You cannot specify a
$naturalsort on a view.For example, the following operation is invalid:
db.view.find().sort({$natural: 1})
Projection Restrictions
find() operations on views do not support the following projection operators:
Immutable Name
You cannot rename views.
View Creation
- Views are computed on demand during read operations, and MongoDB executes read operations on views as part of the underlying aggregation pipeline. As such, views do not support operations such as:
db.collection.mapReduce(),$textoperator, since$textoperation in aggregation is valid only for the first stage,geoNearcommand and$geoNearpipeline stage.
- If the aggregation pipeline used to create the view suppresses the
_idfield, documents in the view do not have the_idfield.
Views and Collation
- 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
$lookupor$graphLookup, the views must have the same collation.
Access Control
If the deployment enforces authentication/authorization, db.createView() requires the following privileges:
createCollectionon the databaseor
createCollectionon the database andfindon the source collection/viewor
createCollectionon the database,findon the view to create, andfindon the source collection/view
A user with createCollection on the database and find on the view to create does not have sufficient privileges.
The readWrite built in role includes the required privileges. Alternatively, you can create a custom role to support db.createView().
The following example uses the db.createUser() method to create a user in the admin database with the readWrite role on the inventory and employees database:
db.getSiblingDB("admin").createUser(
{
"user" : "createViewUser",
"pwd" : "replaceThisWithASecurePassword",
"roles" : [
{ "db" : "inventory", "role" : "readWrite" },
{ "db" : "employees", "role" : "readWrite" }
]
}
)
The created user can execute db.createView() on the specified databases. For more examples of user creation, see Add Users.
Alternatively, you can add the required roles to an existing user using db.grantRolesToUser(). For a tutorial on adding privileges to an existing database user, see Modify Access for an Existing User.
Examples
Create a View from a Single Collection
Given a collection survey with the following documents:
{ _id: 1, empNumber: "abc123", feedback: { management: 3, environment: 3 }, department: "A" }
{ _id: 2, empNumber: "xyz987", feedback: { management: 2, environment: 3 }, department: "B" }
{ _id: 3, empNumber: "ijk555", feedback: { management: 3, environment: 4 }, department: "A" }
The following operation creates a managementFeedback view with the _id, feedback.management, and department fields:
db.createView(
"managementFeedback",
"survey",
[ { $project: { "management": "$feedback.management", department: 1 } } ]
)