On this page本页内容
db.createView()
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.MongoDB对视图执行读取操作,作为底层聚合管道的一部分。
The view definition 视图定义pipeline
cannot include the $out
or the $merge
stage. pipeline
不能包含$out
或$merge
阶段。If the view definition includes nested pipeline (e.g. the view definition includes 如果视图定义包括嵌套管道(例如,视图定义包括$lookup
or $facet
stage), this restriction applies to the nested pipelines as well.$lookup
或$facet
阶段),则此限制也适用于嵌套管道。
The db.createView()
has the following syntax:db.createView()
具有以下语法:
db.createView(<view>, <source>, <pipeline>, <options>)
The method accepts the following parameters:该方法接受以下参数:
view | string | |
source | string | |
pipeline | array |
|
options | document |
The options document contains the following option field:选项文档包含以下选项字段:
collation | document |
collation: { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int>, numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean> }
|
The db.createView()
method wraps the following create
command operation:db.createView()
方法包装了以下create
命令操作:
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.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. db.getCollectionInfos()
和explain
视图上的操作将包括定义视图的管道。As such, avoid referring directly to sensitive fields and values in view definitions.因此,避免在视图定义中直接引用敏感字段和值。
To remove a view, use the 要删除视图,请在视图上使用drop()
method on the view.drop()
方法。
Views exhibit the following behavior:视图显示以下行为:
Views are read-only; write operations on views will error.视图是只读的;对视图的写入操作将出错。
The following read operations can support views:以下读取操作可以支持视图:
$natural
sort when running a find
command on a view. find
命令时指定$natural
排序。$natural
sort on views.$natural
排序。The view's underlying aggregation pipeline is subject to the 100 megabyte memory limit for blocking sort and blocking group operations. 视图的底层聚合管道受阻塞排序和阻塞组操作的100 MB内存限制的限制。Starting in MongoDB 4.4, you can issue a 从MongoDB 4.4开始,您可以在视图上发出一个带有find
command with allowDiskUse: true
on the view to allow MongoDB to use temporary files for blocking sort and group operations.allowDiskUse:true
的find
命令,以允许MongoDB使用临时文件来阻止排序和分组操作。
Prior to MongoDB 4.4, only the 在MongoDB 4.4之前,只有aggregate
command accepted the allowDiskUse
option.aggregate
命令接受allowDiskUse
选项。
For more information on blocking sort operation memory limits, see Sort Operations.有关阻止排序操作内存限制的更多信息,请参阅排序操作。
find()
operations on views do not support the following projection operators:视图上的操作不支持以下投影运算符:
Views are computed on demand during read operations, and MongoDB executes read operations on views as part of the underlying aggregation pipeline. 视图是在读取操作期间按需计算的,MongoDB作为底层聚合管道的一部分对视图执行读取操作。As such, views do not support operations such as:因此,视图不支持以下操作:
db.collection.mapReduce()
,$text
operator, since $text
operation in aggregation is valid only for the first stage,$text
运算符,因为聚合中的$text
操作仅对第一阶段有效,$geoNear
_id
field, documents in the view do not have the _id
field._id
字段,则视图中的文档没有_id
字段。When you query a view, the:查询视图时,将:
filter
, projection
, sort
, skip
, limit
, and other operations for db.collection.find()
are converted to the equivalent aggregation pipeline stages.db.collection.find()
的查询filter
、projection
、sort
、skip
、limit
和其他操作被转换为等效的聚合管道阶段。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.$lookup
和$graphLookup
操作中为from
字段指定分片视图。
$lookup
or $graphLookup
, the views must have the same collation.$lookup
或$graphLookup
,则视图必须具有相同的排序规则。Changed in version 4.2.在版本4.2中更改。
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()
释放锁。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. system.views
集合上获得额外的独占锁。This lock blocks creation or modification of views in the database until the command completes.此锁定将阻止创建或修改数据库中的视图,直到命令完成。
Prior to MongoDB 4.2, 在MongoDB 4.2之前,db.createView()
obtained an exclusive lock on the parent database, blocking all operations on the database andall its collections until the operation completed.db.createView()
在父数据库上获得了一个独占锁,阻止了数据库及其所有集合上的所有操作,直到操作完成。
If the deployment enforces authentication, 如果部署强制身份验证,则db.createView()
requires that the authenticated user have the createCollection
privilege on the database.db.createView()
要求经过身份验证的用户对数据库具有createCollection
权限。
However, if the user has the 但是,如果用户在数据库上拥有createCollection
on the database and find
on the view to create, the user must also have the following additional permissions:createCollection
,并在视图上find
要创建的内容,则用户还必须具有以下附加权限:
find
find
on any other collections or views referenced in the pipeline
, if any.find
管道中引用的任何其他集合或视图(如果有)。A user with the 数据库上具有内置readWrite
built in role on the database has the required privileges to run the listed operations. readWrite
角色的用户具有运行所列操作所需的权限。Either create a user with the required role or grant the role to an existing user创建具有所需角色的用户,或将该角色授予现有用户。
Given a collection 给定带有以下文档的集合survey
with the following documents:survey
:
{ _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:_id
、feedbackmanagement
和department
字段的managementFeedback
视图:
db.createView( "managementFeedback", "survey", [ { $project: { "management": "$feedback.management", department: 1 } } ] )
To query the view, you can use 要查询视图,可以在视图上使用db.collection.find()
on the view:db.collection.find()
:
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 }
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:managementFeedback
视图上执行聚合,使用$sortByCount
按department
字段分组,并按每个不同部门的计数降序排序:
db.managementFeedback.aggregate([ { $sortByCount: "$department" } ] )
The operation returns the following documents:操作将返回以下文档:
{ "_id" : "A", "count" : 2 } { "_id" : "B", "count" : 1 }
Given the following two collections:给定以下两个集合:
The orders
collection:orders
集合:
{ "_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:inventory
集合
{ "_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()
示例指定$lookup
阶段,以从两个集合的连接创建视图:
db.createView ( "orderDetails", "orders", [ { $lookup: { from: "inventory", localField: "item", foreignField: "sku", as: "inventory_docs" } }, { $project: { "inventory_docs._id": 0, "inventory_docs.sku": 0 } } ] )
To query the view, you can use 要查询视图,可以在视图上使用db.collection.find()
on the view:db.collection.find()
:
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 } ] }
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:orderDetails
视图上执行聚合,使用$sortByCount
按项字段分组,并按每个不同项的计数按降序排序:
db.orderDetails.aggregate( [ { $sortByCount: "$item" } ] )
The operation returns the following documents:操作将返回以下文档:
{ "_id" : "xyz", "count" : 2 } { "_id" : "abc", "count" : 2 } { "_id" : "jkl", "count" : 1 }
Given the 给定带有以下文档的places
collection with the following document:places
集合:
{ _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
.3
。
An operation that attempts to change or override a view's default collation will fail with an error.尝试更改或覆盖视图的默认排序规则的操作将失败,并出现错误。