On this page本页内容
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
.create
的包装器。
The db.createCollection()
method has the following prototype form:db.createCollection()
方法具有以下原型形式:
MongoDB removes the MMAPv1 storage engine and the MMAPv1 specific options MongoDB对paddingFactor
, paddingBytes
, preservePadding
for db.createCollection()
.db.createCollection()
删除了MMAPv1存储引擎和MMAPv1-specific选项paddingFactor
、paddingBytes
、preserveAdding
。
db.createCollection( <name>, { capped: <boolean>, timeseries: { // Added in MongoDB 5.0 timeField: <string>, // required for time series collections metaField: <string>, granularity: <string> }, expireAfterSeconds: <number>, 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()
方法具有以下参数:
name | string | |
options | document |
The options
document contains the following fields:options
文档包含以下字段:
capped | boolean | true . true 。true , you must also set a maximum size in the size field.true ,还必须在size 字段中设置最大大小。 | ||||||||
timeseries.timeField | string | timeField .timeField 的值。 | ||||||||
timeseries.metaField | string |
| ||||||||
timeseries.granularity | string | "seconds" (default), "minutes" , and "hours" . "seconds" (默认)、"minutes" 和"hours" 。granularity parameter improves performance by optimizing how data in the time series collection is stored internally. | ||||||||
expireAfterSeconds | number | |||||||||
autoIndexId | boolean |
| ||||||||
size | number | size field is required for capped collections and ignored for other collections. size 字段对于封顶集合是必需的,对于其他集合则被忽略。 | ||||||||
max | number | size limit takes precedence over this limit. size 限制优先于此限制。size limit before it reaches the maximum number of documents, MongoDB removes old documents. size 限制,MongoDB将删除旧文档。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 |
{ <storage-engine-name>: <options> }
| ||||||||
validator | document |
| ||||||||
validationLevel | string |
| ||||||||
validationAction | string |
| ||||||||
indexOptionDefaults | document |
{ <storage-engine-name>: <options> }
| ||||||||
viewOn | string |
| ||||||||
pipeline | array |
| ||||||||
collation | document |
collation: { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int>, numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean> }
| ||||||||
writeConcern | document |
|
If the deployment enforces authentication/authorization, 如果部署强制执行身份验证/授权,db.createCollection()
requires the following privileges:db.createCollection()
需要以下权限:
Task | |
---|---|
| |
| |
|
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.创建具有所需角色的用户或将角色授予现有用户。
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, 在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.db.createCollection()
获得了父数据库上的独占锁,阻塞了数据库及其所有集合上的所有操作,直到操作完成。
Changed in version 4.4.在版本4.4中更改。
Starting in MongoDB 4.4, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.从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"
,则事务将失败。
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. 如果集合在达到最大文档数之前达到最大大小限制,MongoDB将删除较旧的文档。Consider the following example:考虑以下示例:
db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
This command creates a collection named 此命令创建一个名为log的集合,最大大小为5 MB,最多5000个文档。log
with a maximum size of 5 megabytes and a maximum of 5000 documents.
See Capped Collections for more information about capped collections.有关封顶集合的详细信息,请参阅封顶集合。
To create a time series collection that captures weather data for the past 24 hours, issue this command:要创建捕获过去24小时天气数据的时间序列集合,请发出以下命令:
db.createCollection( "weather24h", { timeseries: { timeField: "timestamp", metaField: "data", granularity: "hours" }, expireAfterSeconds: 86400 } )
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.validationLevel
和validationAction
,MongoDB要么返回警告,要么在文档未满足指定条件时拒绝插入或更新文档。
The following example creates a 以下示例使用JSON模式验证器创建contacts
collection with a JSON Schema validator:contacts
集合:
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" } } } } } )
With the validator in place, the following insert operation fails validation:验证程序就位后,以下插入操作将无法通过验证:
db.contacts.insertOne( { name: "Amanda", status: "Updated" } )
The method returns the error:该方法返回错误:
Uncaught: MongoServerError: Document failed validation Additional information: { failingDocumentId: ObjectId("61a8f4847a818411619e952e"), details: { operatorName: '$jsonSchema', schemaRulesNotSatisfied: [ { operatorName: 'properties', propertiesNotSatisfied: [ { propertyName: 'status', description: 'can only be one of the enum values', details: [ [Object] ] } ] }, { operatorName: 'required', specifiedAs: { required: [ 'phone' ] }, missingProperties: [ 'phone' ] } ] } }
To view the validation specifications for a collection, use 要查看集合的验证规范,请使用db.getCollectionInfos()
.db.getCollectionInfos()
。
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é" }
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 此操作使用MongoDB将传递给users
with a specific configuration string that MongoDB will pass to the wiredTiger
storage engine. wiredTiger
存储引擎的特定配置字符串创建一个名为users
的新集合。See the WiredTiger documentation of collection level options for specific 有关特定的wiredTiger
options.WiredTiger
选项,请参阅集合级别选项的WiredTiger文档。