Navigation

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. MongoDB executes read operations on views as part of the underlying aggregation pipeline.

The db.createView has the following syntax:

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

The method accepts the following parameters:

Parameter Type Description
view string The name of the view to create.
source string 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.
pipeline array

An array that consists of the aggregation pipeline stage. db.createView creates the view by applying the specified pipeline to the source collection or view.

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.

options document Optional. Additional options for the method.

The options document contains the following option field:

Field Type Description
collation document

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 source is 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 source is 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 locale field 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 following create command operation:

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

Operations that lists collections, such as db.getCollectionInfos() and db.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 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.

Index Use and Sort Operations

  • Views use indexes of the underlying collection.
  • You cannot specify a $natural sort on a view.

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:
  • 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 is sharded. As such, you cannot specify a sharded view for the from field in $lookup and $graphLookup operations.

For example, the following operation is invalid:

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

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 $lookup or $graphLookup, the views must have the same collation.

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 managementRatings view with the _id, feedback.management, and department fields:

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

Query a View

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

db.managementFeedback.find()

The operation returns the following documents:

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

Perform Aggregation Pipeline on a View

The following operation performs an aggregation on the managementFeedback view, using the $sortByCount to group by the department field and sort in descending order by the count of each distinct department:

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

The operation returns the following documents:

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

Create a View from Multiple Collections

Given the following two collections:

  • The orders collection:

    { "_id" : 1, "item" : "abc", "price" : NumberDecimal("12.00"), "quantity" : 2 }
    { "_id" : 2, "item" : "jkl", "price" : NumberDecimal("20.00"), "quantity" : 1 }
    { "_id" : 3, "item" : "abc", "price" : NumberDecimal("10.95"), "quantity" : 5 }
    { "_id" : 4, "item" : "xyz", "price" : NumberDecimal("5.95"), "quantity" : 5 }
    { "_id" : 5, "item" : "xyz", "price" : NumberDecimal("5.95"), "quantity" : 10 }
    
  • The inventory collection:

    { "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }
    { "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80 }
    { "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 }
    { "_id" : 4, "sku" : "jkl", description: "product 4", "instock" : 70 }
    { "_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 two collections:

db.createView (
   "orderDetails",
   "orders",
   [
     { $lookup: { from: "inventory", localField: "item", foreignField: "sku", as: "inventory_docs" } },
     { $project: { "inventory_docs._id": 0, "inventory_docs.sku": 0 } }
   ]
)

Query a View

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

db.orderDetails.find()

The operation returns the following documents:

{
   "_id" : 1,
   "item" : "abc",
   "price" : NumberDecimal("12.00"),
   "quantity" : 2,
   "inventory_docs" : [ { "description" : "product 1", "instock" : 120 } ]
}
{
   "_id" : 2,
   "item" : "jkl",
   "price" : NumberDecimal("20.00"),
   "quantity" : 1,
   "inventory_docs" : [ { "description" : "product 4", "instock" : 70 } ]
}
{
   "_id" : 3,
   "item" : "abc",
   "price" : NumberDecimal("10.95"),
   "quantity" : 5,
   "inventory_docs" : [ { "description" : "product 1", "instock" : 120 } ]
}
{
   "_id" : 4,
   "item" : "xyz",
   "price" : NumberDecimal("5.95"),
   "quantity" : 5,
   "inventory_docs" : [ { "description" : "product 5", "instock" : 200 } ]
}
{
   "_id" : 5,
   "item" : "xyz",
   "price" : NumberDecimal("5.95"),
   "quantity" : 10,
   "inventory_docs" : [ { "description" : "product 5", "instock" : 200 } ]
}

Perform Aggregation Pipeline on a View

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

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

The operation returns the following documents:

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

Create a View with Default Collation

Given the places collection with the following document:

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

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

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

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

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

The operation returns 3.

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