db.createView()

  • db.createView()

Note

The following page discusses views. For discussion of on-demandmaterialized views, see $merge instead.

Creates a view as the result of the applyingthe specified aggregation pipeline tothe source collection or view. Views act as read-only collections,and are computed on demand during read operations. You must createviews in the same database as the source collection. MongoDBexecutes read operations on views as part of the underlyingaggregation pipeline.

The view definition pipeline cannotinclude the $out or the $merge stage. If the view definition includesnested pipeline (e.g. the view definition includes$lookup or $facet stage), thisrestriction applies to the nested pipelinesas well.

The db.createView has the following syntax:

  1. db.createView(<view>, <source>, <pipeline>, <options>)

The method accepts the following parameters:

ParameterTypeDescriptionviewstringThe name of the view to create.sourcestringThe name of the source collection or view from which to create theview. The name is not the full namespace of the collection orview; i.e. does not include the database name and implies the samedatabase as the view to create. You must create views in the samedatabase as the source collection.pipelinearrayAn array that consists of the aggregation pipeline stage(s). db.createView creates the view byapplying the specified pipeline to the source collection or view.

The view definition pipeline cannotinclude the $out or the $merge stage. If the view definition includesnested pipeline (e.g. the view definition includes$lookup or $facet stage), thisrestriction applies to the nested pipelinesas well.

The view definition is public; i.e. db.getCollectionInfos()and explain operations on the view will include the pipeline thatdefines the view. As such, avoid referring directly to sensitive fieldsand values in view definitions.optionsdocumentOptional. Additional options for the method.

The options document contains the following option field:

FieldTypeDescriptioncollationdocumentOptional. Specifies the default collation for the view.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

If the underlying source is a collection, the view does notinherit the collection’s collation settings.

If no collation is specified, the view’s default collation is the“simple” binary comparison collator.

If the underlying source is another view, the view must specifythe same collation settings.

The collation option has the following syntax:

  1. collation: {
  2. locale: <string>,
  3. caseLevel: <boolean>,
  4. caseFirst: <string>,
  5. strength: <int>,
  6. numericOrdering: <boolean>,
  7. alternate: <string>,
  8. maxVariable: <string>,
  9. backwards: <boolean>
  10. }

When specifying collation, the locale field is mandatory; allother collation fields are optional. For descriptions of the fields,see Collation Document.

New in version 3.4.

The db.createView() method wraps the followingcreate command operation:

  1. db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline>, collation: <collation> } )

Operations that lists collections, such asdb.getCollectionInfos() anddb.getCollectionNames(), includes views in their outputs.

Important

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

To remove a view, use the drop() method on theview.

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 cannotcreate, drop or re-build indexes on the view directly nor get alist of indexes on the view.

  • You cannot specify a $natural sort on a view.

For example, the following operation is invalid:

  1. db.view.find().sort({$natural: 1})

Projection Restrictions

find() operations on views do not supportthe following projectionoperators:

Immutable Name

You cannot rename views.

View Creation

  • Views are computed on demand during read operations, and MongoDBexecutes read operations on views as part of the underlyingaggregation pipeline. As such, views do not support operationssuch as:
  • If the aggregation pipeline used to create the view suppresses the_id field, documents in the view do not have the _id field.

Sharded View

Views are considered sharded if their underlying collection issharded. As such, you cannot specify a sharded view for the fromfield in $lookup and $graphLookup operations.

Views and Collation

  • You can specify a default collationfor a view at creation time. If no collation is specified, theview’s default collation is the “simple” binary comparisoncollator. That is, the view does not inherit the collection’sdefault collation.
  • String comparisons on the view use the view’s default collation.An operation that attempts to change or override a view’s defaultcollation will fail with an error.
  • If creating a view from another view, you cannot specify acollation that differs from the source view’s collation.
  • If performing an aggregation that involves multiple views, such aswith $lookup or $graphLookup, the views musthave the same collation.

Resource Locking

Changed in version 4.2.

db.createView() obtains an exclusive lock on thespecified collection or view for the duration of the operation. Allsubsequent operations on the collection must wait untildb.createView() releases the lock. db.createView() typically holdsthis lock for a short time.

Creating a view requires obtaining an additional exclusive lockon the system.views collection in the database. This lock blockscreation or modification of views in the database until the commandcompletes.

Prior to MongoDB 4.2, db.createView() obtained an exclusive lockon the parent database, blocking all operations on the database _and_all its collections until the operation completed.

Access Control

If the deployment enforcesauthentication/authorization,db.createView() requires the following privileges:

or

or

A user with createCollection on the databaseand find on the view to create does not have sufficientprivileges.

The readWrite built in role includes the requiredprivileges. Alternatively, you cancreate a custom role to supportdb.createView().

The following example uses the db.createUser() method tocreate a user in the admin database with the readWriterole on the inventory and employees database:

  1. db.getSiblingDB("admin").createUser(
  2. {
  3. "user" : "createViewUser",
  4. "pwd" : "replaceThisWithASecurePassword",
  5. "roles" : [
  6. { "db" : "inventory", "role" : "readWrite" },
  7. { "db" : "employees", "role" : "readWrite" }
  8. ]
  9. }
  10. )

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 userusing db.grantRolesToUser(). For a tutorial on addingprivileges to an existing database user, seeModify Access for an Existing User.

Examples

Create a View from a Single Collection

Given a collection survey with the following documents:

  1. { _id: 1, empNumber: "abc123", feedback: { management: 3, environment: 3 }, department: "A" }
  2. { _id: 2, empNumber: "xyz987", feedback: { management: 2, environment: 3 }, department: "B" }
  3. { _id: 3, empNumber: "ijk555", feedback: { management: 3, environment: 4 }, department: "A" }

The following operation creates a managementRatings view withthe _id, feedback.management, and department fields:

  1. db.createView(
  2. "managementFeedback",
  3. "survey",
  4. [ { $project: { "management": "$feedback.management", department: 1 } } ]
  5. )

Query a View

To query the view, you can use db.collection.find() onthe view:

  1. db.managementFeedback.find()

The operation returns the following documents:

  1. { "_id" : 1, "department" : "A", "management" : 3 }
  2. { "_id" : 2, "department" : "B", "management" : 2 }
  3. { "_id" : 3, "department" : "A", "management" : 3 }

Perform Aggregation Pipeline on a View

The following operation performs an aggregation on themanagementFeedback view, using the $sortByCount togroup by the department field and sort in descending order by thecount of each distinct department:

  1. db.managementFeedback.aggregate([ { $sortByCount: "$department" } ] )

The operation returns the following documents:

  1. { "_id" : "A", "count" : 2 }
  2. { "_id" : "B", "count" : 1 }

Create a View from Multiple Collections

Given the following two collections:

  • The orders collection:
  1. { "_id" : 1, "item" : "abc", "price" : NumberDecimal("12.00"), "quantity" : 2 }
  2. { "_id" : 2, "item" : "jkl", "price" : NumberDecimal("20.00"), "quantity" : 1 }
  3. { "_id" : 3, "item" : "abc", "price" : NumberDecimal("10.95"), "quantity" : 5 }
  4. { "_id" : 4, "item" : "xyz", "price" : NumberDecimal("5.95"), "quantity" : 5 }
  5. { "_id" : 5, "item" : "xyz", "price" : NumberDecimal("5.95"), "quantity" : 10 }
  • The inventory collection:
  1. { "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }
  2. { "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80 }
  3. { "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 }
  4. { "_id" : 4, "sku" : "jkl", description: "product 4", "instock" : 70 }
  5. { "_id" : 5, "sku" : "xyz", description: "product 5", "instock" : 200 }

The following db.createView() example specifies a$lookup stage to create a view from the join of the twocollections:

  1. db.createView (
  2. "orderDetails",
  3. "orders",
  4. [
  5. { $lookup: { from: "inventory", localField: "item", foreignField: "sku", as: "inventory_docs" } },
  6. { $project: { "inventory_docs._id": 0, "inventory_docs.sku": 0 } }
  7. ]
  8. )

Query a View

To query the view, you can use db.collection.find() onthe view:

  1. db.orderDetails.find()

The operation returns the following documents:

  1. {
  2. "_id" : 1,
  3. "item" : "abc",
  4. "price" : NumberDecimal("12.00"),
  5. "quantity" : 2,
  6. "inventory_docs" : [ { "description" : "product 1", "instock" : 120 } ]
  7. }
  8. {
  9. "_id" : 2,
  10. "item" : "jkl",
  11. "price" : NumberDecimal("20.00"),
  12. "quantity" : 1,
  13. "inventory_docs" : [ { "description" : "product 4", "instock" : 70 } ]
  14. }
  15. {
  16. "_id" : 3,
  17. "item" : "abc",
  18. "price" : NumberDecimal("10.95"),
  19. "quantity" : 5,
  20. "inventory_docs" : [ { "description" : "product 1", "instock" : 120 } ]
  21. }
  22. {
  23. "_id" : 4,
  24. "item" : "xyz",
  25. "price" : NumberDecimal("5.95"),
  26. "quantity" : 5,
  27. "inventory_docs" : [ { "description" : "product 5", "instock" : 200 } ]
  28. }
  29. {
  30. "_id" : 5,
  31. "item" : "xyz",
  32. "price" : NumberDecimal("5.95"),
  33. "quantity" : 10,
  34. "inventory_docs" : [ { "description" : "product 5", "instock" : 200 } ]
  35. }

Perform Aggregation Pipeline on a View

The following operation performs an aggregation on the orderDetailsview, using the $sortByCount to group by the itemfield and sort in descending order by the count of each distinct item:

  1. db.orderDetails.aggregate( [ { $sortByCount: "$item" } ] )

The operation returns the following documents:

  1. { "_id" : "xyz", "count" : 2 }
  2. { "_id" : "abc", "count" : 2 }
  3. { "_id" : "jkl", "count" : 1 }

Create a View with Default Collation

Given the places collection with the following document:

  1. { _id: 1, category: "café" }
  2. { _id: 2, category: "cafe" }
  3. { _id: 3, category: "cafE" }

The following operation creates a view, specifying collation at the view level:

  1. db.createView(
  2. "placesView",
  3. "places",
  4. [ { $project: { category: 1 } } ],
  5. { collation: { locale: "fr", strength: 1 } }
  6. )

String comparisons on the view use the view’s default collation. Forexample, the following operation uses the view’s collation:

  1. db.placesView.count( { category: "cafe" } )

The operation returns 3.

An operation that attempts to change or override a view’s defaultcollation will fail with an error.

See also

Collation and Views