Docs HomeMongoDB Manual

Create and Query a View创建和查询视图

To create a view, use db.createCollection() or db.createView().要创建视图,请使用db.createCollection()db.createView()

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.列出集合的操作,如db.getCollectionInfos()db.getCollectionNames(),在其输出中包含视图。

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.getCollectionInfos()explain对视图的操作将包括定义视图的管道。因此,请避免直接引用视图定义中的敏感字段和值。

db.createCollection() Syntax语法

db.createCollection(
"<viewName>",
{
"viewOn" : "<source>",
"pipeline" : [<pipeline>],
"collation" : { <collation> }
}
)

db.createView() Syntax语法

db.createView(
"<viewName>",
"<source>",
[<pipeline>],
{
"collation" : { <collation> }
}
)

Restrictions限制

  • You must create views in the same database as the source collection.您必须在与源集合相同的数据库中创建视图。

  • A view definition pipeline cannot include the $out or the $merge stage. 视图定义pipeline不能包含$out$merge阶段。This restriction also applies to embedded pipelines, such as pipelines used in $lookup or $facet stages.此限制也适用于嵌入式管道,例如$lookup$facet阶段中使用的管道。

  • You cannot rename a view once it is created.创建视图后,不能对其进行重命名。

Unsupported Operations不支持的操作

Some operations are not available with views:某些操作不可用于视图:

  • db.collection.mapReduce().

  • $text operator, since $text operation in aggregation is valid only for the first stage.$text运算符,因为聚合中的$text操作仅对第一阶段有效。

  • $geoNear pipeline stage.管道阶段。

  • Renaming a view.重命名视图。

For more information, see Supported Operations for Views.有关详细信息,请参阅支持视图的操作

Example实例

This example populates a collection with student data and creates a view to query the data.此示例使用学生数据填充集合,并创建一个视图来查询数据。

Populate the Collection填充集合

Create a students collection to use for this example:创建students集合以用于此示例:

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使用db.createView()创建视图

Use db.createView() to create a view that is limited to first year students:使用db.createView()创建一个仅限一年级学生使用的视图:

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.是一个聚合表达式,与students集合中的一年级学生相匹配。

Query the View查询视图

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.{ _id: 0 }投影抑制输出中的_id字段。

[
{ 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 Query and Projection Operators operators:视图上的find()操作不支持以下查询和投影运算符

Use db.createCollection() to Create a View

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.

Query the View

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 }
]

Behavior行为

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

Aggregation Optimizations

When you query a view:

  • Query filter, projection, sort, skip, limit, and other operations for db.collection.find() are converted to the equivalent aggregation pipeline stages.

  • MongoDB appends the client query to the underlying pipeline and returns the results of that combined pipeline to the client. MongoDB may apply aggregation pipeline optimizations to the combined pipeline.

  • The aggregation pipeline optimizer reshapes the view aggregation pipeline stages to improve performance. The optimization does not change the query results.

Resource Locking

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.