Create and Query a View创建和查询视图
On this page
db.createCollection()
Syntaxdb.createView()
SyntaxRestrictions限制Unsupported Operations不支持的操作Example实例Populate the Collection填充集合Use db.createView() to Create a View使用db.createView()
创建视图Use db.createCollection() to Create a View使用db.createCollection()
创建视图Behavior行为Aggregation Optimizations聚合优化Resource Locking资源锁定
To create a view, use 要创建视图,请使用db.createCollection()
or db.createView()
.db.createCollection()
或db.createView()
。
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:某些操作不可用于视图:
-
$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 }
]
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" }
}
)
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 fordb.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.