Definition定义
db.createCollection(name, options)Creates a new collection. For views, see创建新集合。有关视图,请参阅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. For example, you use由于MongoDB在命令中首次引用集合时隐式创建集合,因此此方法主要用于创建使用特定选项的新集合。例如,您可以使用db.createCollection()to create a:db.createCollection()创建一个:Capped collection.封顶集合。Clustered collection.集群集合。New collection that uses schema validation.使用架构验证的新集合。
db.createCollection()is a wrapper around the database command是数据库命令create.create的包装器。
Compatibility兼容性
This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Note
This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Syntax语法
The db.createCollection() method has the following prototype form:db.createCollection()方法具有以下原型形式:
db.createCollection( <name>,
{
capped: <boolean>,
timeseries: { // Added in MongoDB 5.0
timeField: <string>, // required for time series collections
metaField: <string>,
granularity: <string>,
bucketMaxSpanSeconds: <number>, // Added in MongoDB 6.3
bucketRoundingSeconds: <number> // Added in MongoDB 6.3
},
expireAfterSeconds: <number>,
clusteredIndex: <document>, // Added in MongoDB 5.3
changeStreamPreAndPostImages: <document>, // Added in MongoDB 6.0
size: <number>,
max: <number>,
storageEngine: <document>,
validator: <document>,
validationLevel: <string>,
validationAction: <string>,
indexOptionDefaults: <document>,
viewOn: <string>,
pipeline: <pipeline>,
collation: <document>,
writeConcern: <document>
}
)
The db.createCollection() method has the following parameters:db.createCollection()方法具有以下参数:
name | ||
options |
|
The options document contains the following fields:options文档包含以下字段:
capped | true. If you specify true, you must also set a maximum size in the size field.true。如果指定true,则还必须在size字段中设置最大大小。 | |
timeseries.timeField | timeField.timeField的值。 | |
timeseries.metaField |
| |
timeseries.granularity |
| |
timeseries.bucketMaxSpanSeconds |
| |
timeseries.bucketRoundingSeconds |
| |
expireAfterSeconds |
| |
clusteredIndex |
| |
changeStreamPreAndPostImages |
| |
size | size field is required for capped collections and ignored for other collections.size字段对于有上限的集合是必需的,对于其他集合则忽略。 | |
max | 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 |
| |
validator |
| |
validationLevel |
| |
validationAction |
| |
indexOptionDefaults |
| |
viewOn | db.createView().db.createView()。 | |
pipeline | db.createView() creates a view by applying the specified pipeline to the viewOn collection or view. For details, see db.createView().db.createView()通过将指定的pipeline应用于viewOn集合或视图来创建视图。有关详细信息,请参阅db.createView()。 | |
collation |
| |
writeConcern |
|
Access Control访问控制
If the deployment enforces authentication/authorization, 如果部署强制执行身份验证/授权,db.createCollection() requires the following privileges:db.createCollection()需要以下权限:
| |
| |
|
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行为
db.createCollection() has the following behavior:具有以下行为:
Resource Locking资源锁定
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() typically holds this lock for a short time.db.createCollection()释放锁。db.createCollection()通常会在短时间内保持此锁。
Creating a view requires obtaining an additional exclusive lock on the 创建视图需要在数据库中的system.views collection in the database. This lock blocks creation or modification of views in the database until the command completes.system.views集合上获得额外的独占锁。此锁会阻止在命令完成之前创建或修改数据库中的视图。
Transactions事务
You can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.如果分布式事务不是跨分片写入事务,则可以在该事务内创建集合和索引。
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"以外的读取关注级别,则事务失败。
Collection or View with Same Name and Options具有相同名称和选项的集合或视图
If you run 如果您以与现有集合或视图相同的名称和选项运行db.createCollection() with the same name and options as an existing collection or view, db.createCollection() returns success.db.createCollection(),db.createCollection()将返回成功。
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 MB,最多可包含5000个文档。
See Capped Collections for more information about capped collections.有关封顶集合的更多信息,请参阅封顶集合。
Create a Time Series Collection创建时间序列集合
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
}
)
Alternately, to create the same collection but limit each bucket to timestamp values within the same hour, issue this command:或者,要创建相同的集合,但将每个桶限制为同一小时内的时间戳值,请发出以下命令:
db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
bucketMaxSpanSeconds: "3600",
bucketRoundingSeconds: "3600"
},
expireAfterSeconds: 86400
}
)Create a Clustered Collection创建群集集合
The following 以下db.createCollection() example adds a clustered collection named stocks:db.createCollection()示例添加了一个名为stocks的集群集合:
db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
In the example, clusteredIndex specifies:在该示例中,clusteredIndex指定:
"key": { _id: 1 }, which sets the clustered index key to the,它将聚集索引键设置为_idfield._id字段。"unique": true, which indicates the clustered index key value must be unique.,这表示聚集索引键值必须是唯一的。"name": "stocks clustered key", which sets the clustered index name.,它设置聚集索引名称。
Create a Collection with Change Stream Pre- and Post-Images for Documents为文档创建一个包含更改流前后映像的集合
Starting in MongoDB 6.0, you can use change stream events to output the version of a document before and after changes (the document pre- and post-images):从MongoDB 6.0开始,您可以使用更改流事件输出更改前后的文档版本(文档前和后映像):
The pre-image is the document before it was replaced, updated, or deleted. There is no pre-image for an inserted document.前映像是替换、更新或删除之前的文档。插入的文档没有前映像。The post-image is the document after it was inserted, replaced, or updated. There is no post-image for a deleted document.后映像是插入、替换或更新后的文档。已删除文档没有后映像。Enable使用changeStreamPreAndPostImagesfor a collection usingdb.createCollection(),create, orcollMod.db.createCollection()、create或collMod为集合启用changeStreamPreAndPostImages。
The following example creates a collection that has changeStreamPreAndPostImages enabled:以下示例创建了一个启用了changeStreamPreAndPostImages的集合:
db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
);
Pre- and post-images are not available for a change stream event if the images were:如果映像是以下情况,则前后映像对更改流事件不可用:
Not enabled on the collection at the time of a document update or delete operation.在文档更新或删除操作时,集合上未启用。Removed after the pre- and post-image retention time set in在expireAfterSeconds.expireAfterSeconds中设置的映像保留时间前后删除。The following example sets以下示例将整个集群上的expireAfterSecondsto100seconds on an entire cluster:expireAfterSeconds设置为100秒:use admin
db.runCommand( {
setClusterParameter:
{ changeStreamOptions: {
preAndPostImages: { expireAfterSeconds: 100 }
} }
} )The following example returns the current以下示例返回当前changeStreamOptionssettings, includingexpireAfterSeconds:changeStreamOptions设置,包括expireAfterSeconds:db.adminCommand( { getClusterParameter: "changeStreamOptions" } )Setting将expireAfterSecondstooffuses the default retention policy: pre- and post-images are retained until the corresponding change stream events are removed from the oplog.expireAfterSeconds设置为off将使用默认保留策略:保留前后映像,直到从oplog中删除相应的更改流事件。If a change stream event is removed from the oplog, then the corresponding pre- and post-images are also deleted regardless of the如果从oplog中删除了更改流事件,则相应的前映像和后映像也将被删除,而不管映像保留时间为expireAfterSecondspre- and post-image retention time.expireAfterSeconds之前和之后。
Additional considerations:其他注意事项:
Enabling pre- and post-images consumes storage space and adds processing time. Only enable pre- and post-images if you need them.启用前映像和后映像会消耗存储空间并增加处理时间。仅在需要时启用前后映像。Limit the change stream event size to less than 16 mebibytes. To limit the event size, you can:将更改流事件大小限制为小于16兆字节。要限制事件大小,您可以:Limit the document size to 8 megabytes. You can request pre- and post-images simultaneously in the change stream output if other change stream event fields like将文档大小限制为8 MB。如果其他更改流事件字段(如updateDescriptionare not large.updateDescription)不大,您可以在更改流输出中同时请求前映像和后映像。Request only post-images in the change stream output for documents up to 16 mebibytes if other change stream event fields like如果其他更改流事件字段(如updateDescriptionare not large.updateDescription)不大,则仅请求更改流输出中最多16兆字节的文档的后映像。Request only pre-images in the change stream output for documents up to 16 mebibytes if:在以下情况下,仅在更改流输出中请求最多16兆字节的文档的前映像:document updates affect only a small fraction of the document structure or content, and文档更新仅影响文档结构或内容的一小部分,以及do not cause a不要引起replacechange event.replace更换事件。Areplaceevent always includes the post-image.replace事件总是包括后映像。
To request a pre-image, you set要请求前映像,您可以在fullDocumentBeforeChangetorequiredorwhenAvailableindb.collection.watch(). To request a post-image, you setfullDocumentusing the same method.db.collection.watch()中将fullDocumentBeforeChange设置为required或whenAvailable。要请求后映像,您可以使用相同的方法设置fullDocument。Pre-images are written to the前映像会写入config.system.preimagescollection.config.system.preimages集合。Theconfig.system.preimagescollection may become large. To limit the collection size, you can setexpireAfterSecondstime for the pre-images as shown earlier.config.system.preimages集合可能会变大。要限制集合大小,您可以为前映像设置expireAfterSeconds时间,如前所示。Pre-images are removed asynchronously by a background process.前映像由后台进程异步删除。
Important
Backward-Incompatible Feature向后不兼容功能
Starting in MongoDB 6.0, if you are using document pre- and post-images for change streams, you must disable changeStreamPreAndPostImages for each collection using the 从MongoDB 6.0开始,如果您将文档前映像和后映像用于更改流,则必须使用collMod command before you can downgrade to an earlier MongoDB version.collMod命令为每个集合禁用changeStreamPreAndPostImages,然后才能降级到早期的MongoDB版本。
Tip
For change stream events and output, see Change Events.有关更改流事件和输出,请参阅更改事件。To watch a collection for changes, see要查看集合的更改,请参阅db.collection.watch().db.collection.watch()。For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.有关更改流输出的完整示例,请参阅使用文档前后图像更改流。
Specify Collation指定排序规则
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(). Consider the following operation:db.createCollection()创建集合时,可以指定特定于集合的存储引擎配置选项。考虑以下操作:
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存储引擎的特定配置字符串。
For example, to specify the 例如,要为zlib compressor for file blocks in the users collection, set the block_compressor option with the following command:users集合中的文件块指定zlib压缩器,请使用以下命令设置block_compressor选项:
db.createCollection(
"users",
{ storageEngine: { wiredTiger: { configString: "block_compressor=zlib" } } }
)
Starting in MongoDB 7.2, you can't specify 从MongoDB 7.2开始,当您使用wiredTiger storage engine encryption options when you create a collection with db.createCollection(). db.createCollection()创建集合时,您不能指定wiredTiger存储引擎加密选项。To configure encryption for the WiredTiger storage engine, see Encryption at Rest.要为WiredTiger存储引擎配置加密,请参阅静态加密。