db.createCollection()

On this page本页内容

Definition定义

db.createCollection(name, options)

Creates a new collection or view. 创建新的集合或视图For views, see also db.createView().有关视图,请参阅db.createView()

Because MongoDB creates a collection implicitly when the collection is first referenced in a command, this method is used primarily for creating new collections that use specific options. 由于MongoDB在命令中首次引用集合时隐式创建集合,因此此方法主要用于创建使用特定选项的新集合。For example, you use db.createCollection() to create a capped collection, or to create a new collection that uses document validation.例如,您可以使用db.createCollection()创建一个封顶集合,或者创建一个使用文档验证的新集合。

db.createCollection() is a wrapper around the database command create.createCollection()是数据库命令create的包装器。

The db.createCollection() method has the following prototype form:db.createCollection()方法具有以下原型形式:

Starting in MongoDB 4.2

MongoDB removes the MMAPv1 storage engine and the MMAPv1 specific options paddingFactor, paddingBytes, preservePadding for db.createCollection().MongoDB针对db.createCollection()删除了MMAPv1存储引擎和特定于MMAPv1的选项paddingFactorpaddingBytespreservePadding

db.createCollection( <name>,
   {
     capped: <boolean>,
     autoIndexId: <boolean>,
     size: <number>,
     max: <number>,
     storageEngine: <document>,
     validator: <document>,
     validationLevel: <string>,
     validationAction: <string>,
     indexOptionDefaults: <document>,
     viewOn: <string>,              // Added in MongoDB 3.4
     pipeline: <pipeline>,          // Added in MongoDB 3.4
     collation: <document>,         // Added in MongoDB 3.4
     writeConcern: <document>
   }
)

The db.createCollection() method has the following parameters:db.createCollection()方法具有以下参数:

Parameter参数Type类型Description描述
name string The name of the collection to create. 要创建的集合的名称。See Naming Restrictions.请参阅命名限制
options document Optional.可选。Configuration options for creating a capped collection, for preallocating space in a new collection, or for creating a view.用于创建封顶集合、在新集合中预分配空间或创建视图的配置选项。

The options document contains the following fields:options文档包含以下字段:

Field字段Type类型Description描述
capped boolean Optional.可选。To create a capped collection, specify true. 要创建封顶集合,请指定trueIf you specify true, you must also set a maximum size in the size field.如果指定true,则还必须在size字段中设置最大大小。
autoIndexId boolean

Optional.可选。Specify false to disable the automatic creation of an index on the _id field.指定false以禁用在_id字段上自动创建索引。

Important

Starting in MongoDB 4.0, you cannot set the option autoIndexId to false when creating collections in databases other than the local database.从MongoDB 4.0开始,在local数据库以外的数据库中创建集合时,不能将选项autoIndexId设置为false

Deprecated since version 3.2.自版本3.2以来已弃用。

size number Optional.可选。Specify a maximum size in bytes for a capped collection. 指定封顶集合的最大大小(以字节为单位)。Once a capped collection reaches its maximum size, MongoDB removes the older documents to make space for the new documents. 一旦封顶集合达到其最大大小,MongoDB将删除旧文档以为新文档腾出空间。The size field is required for capped collections and ignored for other collections.size字段对于封顶集合是必需的,而对于其他集合则被忽略。
max number Optional.可选。The maximum number of documents allowed in the capped collection. 封顶集合中允许的最大文档数。The size limit takes precedence over this limit. size限制优先于此限制。If a capped collection reaches the size limit before it reaches the maximum number of documents, MongoDB removes old documents. 如果封顶集合在达到最大文档数之前达到size限制,MongoDB将删除旧文档。If you prefer to use the max limit, ensure that the size limit, which is required for a capped collection, is sufficient to contain the maximum number of documents.如果您更喜欢使用max限制,请确保size限制(上限集合所需)足以包含最大数量的文档。
storageEngine document

Optional.可选。Available for the WiredTiger storage engine only.仅适用于WiredTiger存储引擎。

Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection. 允许用户在创建集合时按集合指定存储引擎的配置。The value of the storageEngine option should take the following form:storageEngine选项的值应采用以下形式:

{ <storage-engine-name>: <options> }

Storage engine configuration specified when creating collections are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.创建集合时指定的存储引擎配置将在复制期间验证并记录到oplog,以支持具有使用不同存储引擎的成员的副本集。

validator document

Optional.可选。Allows users to specify validation rules or expressions for the collection. 允许用户为集合指定验证规则或表达式For more information, see Schema Validation.有关更多信息,请参阅架构验证

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

The validator option takes a document that specifies the validation rules or expressions. validator选项接受指定验证规则或表达式的文档。You can specify the expressions using the same operators as the query operators with the exception of $geoNear, $near, $nearSphere, $text, and $where.可以使用与查询运算符相同的运算符指定表达式,但$geoNear$near$nearSphere$text$where除外。

Note

  • Validation occurs during updates and inserts. 在更新和插入期间进行验证。Existing documents do not undergo validation checks until modification.现有文件在修改之前不会进行验证检查。
  • You cannot specify a validator for collections in the admin, local, and config databases.不能为adminlocalconfig数据库中的集合指定验证器。
  • You cannot specify a validator for system.* collections.无法为system.*集合指定验证程序。
validationLevel string

Optional.可选。Determines how strictly MongoDB applies the validation rules to existing documents during an update.确定MongoDB在更新期间对现有文档应用验证规则的严格程度。

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

validationLevelDescription描述
"off" No validation for inserts or updates.没有插入或更新的验证。
"strict" Default Apply validation rules to all inserts and all updates.默认将验证规则应用于所有插入和所有更新。
"moderate" Apply validation rules to inserts and to updates on existing valid documents. 将验证规则应用于插入和现有有效文档的更新。Do not apply rules to updates on existing invalid documents.不要将规则应用于现有无效文档的更新。
validationAction string

Optional.可选。Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted.确定是在无效文档上出错,还是仅对违规行为发出警告,但允许插入无效文档。

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

Important

Validation of documents only applies to those documents as determined by the validationLevel.文件验证仅适用于由validationLevel确定的文件。

validationActionDescription描述
"error" Default Documents must pass validation before the write occurs. 默认在写入之前,文档必须通过验证。Otherwise, the write operation fails.否则,写入操作将失败。
"warn" Documents do not have to pass validation. 文档不必通过验证。If the document fails validation, the write operation logs the validation failure.如果文档验证失败,写入操作将记录验证失败。
indexOptionDefaults document

Optional.可选。Allows users to specify a default configuration for indexes when creating a collection.允许用户在创建集合时为索引指定默认配置。

The indexOptionDefaults option accepts a storageEngine document, which should take the following form:indexOptionDefaults选项接受storageEngine文档,该文档应采用以下形式:

{ <storage-engine-name>: <options> }

Storage engine configuration specified when creating indexes are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.在复制期间验证创建索引时指定的存储引擎配置并将其记录到oplog,以支持具有使用不同存储引擎的成员的副本集。

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

viewOn 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.必须在与源集合相同的数据库中创建视图。

See also db.createView().另请参见db.createView()

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

pipeline array

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

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

See also db.createView().

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

collation document

Specifies the default collation for the collection.指定集合的默认排序规则

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。

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

If you specify a collation at the collection level:如果在集合级别指定排序规则:

  • Indexes on that collection will be created with that collation unless the index creation operation explicitly specify a different collation.除非索引创建操作显式指定不同的排序规则,否则将使用该排序规则创建该集合上的索引。
  • Operations on that collection use the collection’s default collation unless they explicitly specify a different collation.对该集合的操作使用集合的默认排序规则,除非它们显式指定不同的排序规则。

    You cannot specify multiple collations for an operation. 不能为一个操作指定多个排序规则。For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能对查找使用一种排序规则,对排序使用另一种排序规则。

If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.如果没有为集合或操作指定排序规则,MongoDB将使用以前版本中使用的简单二进制比较进行字符串比较。

For a collection, you can only specify the collation during the collection creation. 对于集合,只能在集合创建期间指定排序规则。Once set, you cannot modify the collection’s default collation.设置后,无法修改集合的默认排序规则。

For an example, see Specify Collation.有关示例,请参阅指定排序规则

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

writeConcern document

Optional.可选。A document that expresses the write concern for the operation. 表示操作的写入关注点的文档。Omit to use the default write concern.忽略使用默认的写关注点。

When issued on a sharded cluster, mongos converts the write concern of the create command and its helper db.createCollection() to "majority".在分片集群上发出时,mongos会将create命令及其助手db.createCollection()写关注点转换为"majority"

Access Control访问控制

If the deployment enforces authentication/authorization, db.createCollection() requires the following privileges:如果部署强制进行身份验证/授权db.createCollection()需要以下权限:

 Required Privileges所需特权
Create a non-capped collection创建一个无上限集合

createCollection on the database, or数据库上的createCollection,或

insert on the collection to create在要创建的集合上的insert

Create a capped collection创建一个封顶集合

convertToCapped for the collection集合

createCollection on the database数据库上的createCollection

Create a view创建一个视图

createCollection on the database.数据库上的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
  • find on any other collections or views referenced in the pipeline, if any.查找pipeline中引用的任何其他集合或视图(如果有)上的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.用户将该角色授予现有用户

Behavior行为

Resource Locking资源锁定

Changed in version 4.2.在版本4.2中更改。

db.createCollection() 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.createCollection() releases the lock. 集合上的所有后续操作都必须等待db.createCollection()释放锁。db.createCollection() 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.createCollection() 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.createCollection()获得了父数据库的独占锁,阻止了数据库及其所有集合上的所有操作,直到操作完成。

Transactions事务

Changed in version 4.4.在版本4.4中更改。

Starting in MongoDB 4.4 with feature compatibility version (fcv) "4.4", you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.功能兼容版本(fcv)“4.4”的MongoDB 4.4开始,如果事务不是跨切分写入事务,则可以在多文档事务中创建集合和索引。

To use db.createCollection() in a transaction, the transaction must use read concern "local". 要在事务中使用db.createCollection(),该事务必须使用读关注点"local"If you specify a read concern level other than "local", the transaction fails.如果指定的读取关注级别不是"local",则事务失败。

Examples示例

Create a Capped Collection创建一个封顶集合

Capped collections have maximum size or document counts that prevent them from growing beyond maximum thresholds. 封顶集合具有最大大小或文档计数,可防止其增长超过最大阈值。All capped collections must specify a maximum size and may also specify a maximum document count. 所有封顶集合必须指定最大大小,还可以指定最大文档数。MongoDB removes older documents if a collection reaches the maximum size limit before it reaches the maximum document count. Consider the following example:如果集合在达到最大文档数之前达到最大大小限制,MongoDB将删除旧文档。考虑下面的例子:

db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )

This command creates a collection named log with a maximum size of 5 megabytes and a maximum of 5000 documents.此命令创建一个名为log的集合,最大大小为5兆字节,最大文档数为5000个。

See Capped Collections for more information about capped collections.有关封顶集合的详细信息,请参阅封顶集合

Create a Collection with Document Validation使用文档验证创建集合

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

Collections with validation compare each inserted or updated document against the criteria specified in the validator option. 具有验证的集合将每个插入或更新的文档与validator选项中指定的条件进行比较。Depending on the validationLevel and validationAction, MongoDB either returns a warning, or refuses to insert or update the document if it fails to meet the specified criteria.根据validationLevelvalidationAction,MongoDB要么返回警告,要么拒绝插入或更新未满足指定条件的文档。

The following example creates a contacts collection with a JSON Schema validator:以下示例使用JSON模式验证程序创建contacts集合:

Note

MongoDB 3.6 adds the $jsonSchema operator to support JSON Schema validation.MongoDB 3.6添加了$jsonSchema运算符以支持JSON模式验证。

db.createCollection( "contacts", {
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "phone" ],
      properties: {
         phone: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         email: {
            bsonType : "string",
            pattern : "@mongodb\.com$",
            description: "must be a string and match the regular expression pattern"
         },
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "can only be one of the enum values"
         }
      }
   } }
} )

注:要查看上述集合的架构验证,请使用以下命令:db.getCollectionInfos({name:'contacts'})[0].options.validator.$jsonSchema

With the validator in place, the following insert operation fails validation:验证程序就位后,以下插入操作无法通过验证:

db.contacts.insert( { name: "Amanda", status: "Updated" } )

The method returns the error in the WriteResult:该方法在WriteResult中返回错误:

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 121,
      "errmsg" : "Document failed validation"
   }
})

For more information, see Schema Validation. 有关更多信息,请参阅架构验证To view the validation specifications for a collection, use the db.getCollectionInfos() method.要查看集合的验证规范,请使用db.getCollectionInfos()方法。

Specify Collation指定排序规则

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

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。

You can specify collation at the collection or view level. 可以在集合或视图级别指定排序规则For example, the following operation creates a collection, specifying a collation for the collection (See Collation Document for descriptions of the collation fields):例如,以下操作创建集合,为集合指定排序规则(有关排序规则字段的说明,请参阅排序规则文档):

db.createCollection( "myColl", { collation: { locale: "fr" } } );

This collation will be used by indexes and operations that support collation unless they explicitly specify a different collation. 支持排序规则的索引和操作将使用此排序规则,除非它们显式指定不同的排序规则。For example, insert the following documents into myColl:例如,将以下文档插入myColl

{ _id: 1, category: "café" }
{ _id: 2, category: "cafe" }
{ _id: 3, category: "cafE" }

The following operation uses the collection’s collation:以下操作使用集合的排序规则:

db.myColl.find().sort( { category: 1 } )

The operation returns documents in the following order:该操作按以下顺序返回文档:

{ "_id" : 2, "category" : "cafe" }
{ "_id" : 3, "category" : "cafE" }
{ "_id" : 1, "category" : "café" }

The same operation on a collection that uses simple binary collation (i.e. no specific collation set) returns documents in the following order:对使用简单二进制排序规则(即无特定排序规则集)的集合执行的相同操作将按以下顺序返回文档:

{ "_id" : 3, "category" : "cafE" }
{ "_id" : 2, "category" : "cafe" }
{ "_id" : 1, "category" : "café" }

Specify Storage Engine Options指定存储引擎选项

You can specify collection-specific storage engine configuration options when you create a collection with db.createCollection(). 使用db.createCollection()创建集合时,可以指定特定于集合的存储引擎配置选项。Consider the following operation:考虑以下操作:

db.createCollection(
   "users",
   { storageEngine: { wiredTiger: { configString: "<option>=<setting>" } } }
)

This operation creates a new collection named users with a specific configuration string that MongoDB will pass to the wiredTiger storage engine. 此操作将创建一个名为users的新集合,其中包含MongoDB将传递给wiredTiger存储引擎的特定配置字符串。See the WiredTiger documentation of collection level options for specific wiredTiger options.有关特定的WiredTiger选项,请参阅集合级别选项的WiredTiger文档