db.createView()

On this page本页内容

db.createView()
Note注意

The following page discusses views. For discussion of on-demand materialized views, see $merge instead.下一页讨论视图。有关按需物化视图的讨论,请参阅$merge

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:该方法接受以下参数:

Parameter参数Type类型Description描述
viewstringThe name of the view to create.要创建的视图的名称。
sourcestringThe 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. 名称不是集合或视图的完整命名空间;即,不包括数据库名称,并且暗示与要创建的视图相同的数据库。You must create views in the same database as the source collection.必须在与源集合相同的数据库中创建视图。
pipelinearray

An array that consists of the aggregation pipeline stage(s). 聚合管道阶段组成的数组。db.createView() creates the view by applying the specified pipeline to the source collection or view.通过将指定pipeline应用于source集合或视图来创建视图。

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 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.因此,避免在视图定义中直接引用敏感字段和值。

optionsdocumentOptional. 可选。Additional options for the method.方法的其他选项。

The options document contains the following option field:选项文档包含以下选项字段:

Field字段Type类型Description描述
collationdocument

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.如果基础source是集合,则视图不会继承集合的排序规则设置。

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.如果基础source是另一个视图,则该视图必须指定相同的排序规则设置。

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. 指定排序规则时,locale字段是必需的;所有其他排序规则字段都是可选的。For descriptions of the fields, see Collation Document.有关字段的说明,请参阅排序规则文档

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(),在其输出中包含视图。

Important重要

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()方法。

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 cannot create, drop or re-build indexes on the view directly nor get a list of indexes on the view.由于索引位于基础集合上,因此无法直接在视图上创建、删除或重新生成索引,也无法获取视图上的索引列表。
  • Starting in MongoDB 4.4, you can specify a $natural sort when running a find command on a view. 从MongoDB 4.4开始,您可以在视图上运行find命令时指定$natural排序。Prior versions of MongoDB do not support $natural sort on views.MongoDB的早期版本不支持视图上的$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 find command with allowDiskUse: true on the view to allow MongoDB to use temporary files for blocking sort and group operations.从MongoDB 4.4开始,您可以在视图上发出一个带有allowDiskUse:truefind命令,以允许MongoDB使用临时文件来阻止排序和分组操作。

    Prior to MongoDB 4.4, only the aggregate command accepted the allowDiskUse option.在MongoDB 4.4之前,只有aggregate命令接受allowDiskUse选项。

    Tip提示
    See also: 参阅:

    For more information on blocking sort operation memory limits, see Sort Operations.有关阻止排序操作内存限制的更多信息,请参阅排序操作

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. 视图是在读取操作期间按需计算的,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 pipeline stage.管道阶段。
  • If the aggregation pipeline used to create the view suppresses the _id field, documents in the view do not have the _id field.如果用于创建视图的聚合管道抑制了_id字段,则视图中的文档没有_id字段。

When you query a view, the:查询视图时,将:

  • Query filter, projection, sort, skip, limit, and other operations for db.collection.find() are converted to the equivalent aggregation pipeline stages.db.collection.find()的查询filterprojectionsortskiplimit和其他操作被转换为等效的聚合管道阶段。
  • Converted aggregation pipeline stages are added to the end of the aggregation pipeline for the view. 转换后的聚合管道阶段将添加到视图的聚合管道末端。This does not modify the view's underlying pipeline, which is set when you create the view.这不会修改视图的基础管道,该管道是在创建视图时设置的。
  • Aggregation pipeline optimizer聚合管道优化器 reshapes the view aggregation pipeline stages to improve performance. This does not change the query results.重塑视图聚合管道阶段以提高性能。这不会更改查询结果。

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.因此,不能在$lookup$graphLookup操作中为from字段指定分片视图。

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.如果执行涉及多个视图的聚合,例如使用$lookup$graphLookup,则视图必须具有相同的排序规则

Resource Locking资源锁定

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, db.createView() obtained an exclusive lock on the parent database, blocking all operations on the database andall its collections until the operation completed.在MongoDB 4.2之前,db.createView()在父数据库上获得了一个独占锁,阻止了数据库及其所有集合上的所有操作,直到操作完成。

Access Control访问控制

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 on the source collection or view.在源集合或视图上。
  • 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创建具有所需角色的用户,或将该角色授予现有用户

Examples示例

Create a View from a Single Collection从单个集合创建视图

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:以下操作创建了一个带有_idfeedbackmanagementdepartment字段的managementFeedback视图:

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

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:以下操作在managementFeedback视图上执行聚合,使用$sortByCountdepartment字段分组,并按每个不同部门的计数降序排序:

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

Query a View查询视图

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

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:以下操作在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 }

Create a View with Default Collation创建具有默认排序规则的视图

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.尝试更改或覆盖视图的默认排序规则的操作将失败,并出现错误。

Tip提示
←  db.createCollection()db.currentOp() →