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描述
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. 该名称不是集合或视图的完整命名空间;亦即,不包括数据库名称,并暗示与要创建的视图相同的数据库。You must create views in the same database as the source collection.必须在与源集合相同的数据库中创建视图。
pipeline array

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

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.指定视图的默认db.createView排序规则。

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选项语法如下所示:

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.有关字段的说明,请参阅排序规则文档

New in version 3.4.版本3.4中的新功能。

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选项。

    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:视图上的find()操作不支持以下projection运算符:

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:因此,视图不支持以下操作:
  • 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字段。

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.因此,不能在from field in $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.db.createView()通常会在短时间内持有此锁。

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 and all 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,则该用户还必须具有以下附加权限:

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:以下操作使用_idfeedback.managementdepartment字段创建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视图上执行聚合,使用$sortByCount以按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: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按项目字段分组,并按每个不同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:给定带有以下文档的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.尝试更改或覆盖视图默认排序规则的操作将失败并出现错误。