Definition定义
createExplicitly creates a collection or view.显式创建集合或视图。
Compatibility兼容性
This command 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 create command has the following syntax:create命令具有以下语法:
Note
MongoDB 6.3 adds the bucketMaxSpanSeconds and bucketRoundingSeconds parameters. To downgrade below 6.3, you must either drop all collections with these parameters, or modify them to use the corresponding granularity, if possible. For details see collMod.
db.runCommand(
{
create: <collection or view name>,
capped: <true|false>,
timeseries: {
timeField: <string>,
metaField: <string>,
granularity: <string>,
bucketMaxSpanSeconds: <timespan>, // Added in MongoDB 6.3
bucketRoundingSeconds: <timespan> // Added in MongoDB 6.3
},
expireAfterSeconds: <number>,
clusteredIndex: <document>, // Added in MongoDB 5.3
changeStreamPreAndPostImages: <document>, // Added in MongoDB 6.0
autoIndexId: <true|false>,
size: <max_size>,
max: <max_documents>,
storageEngine: <document>,
validator: <document>,
validationLevel: <string>,
validationAction: <string>,
indexOptionDefaults: <document>,
viewOn: <source>,
pipeline: <pipeline>,
collation: <document>,
writeConcern: <document>,
encryptedFields: <document>,
comment: <any>
}
Command Fields命令字段
The create command has the following fields:create命令包含以下字段:
create | The name of the new collection or view. See Naming Restrictions. If you try to create a collection or view that already exists and you provide identical options for that existing collection or view, no action is taken and success is returned. | |
capped | true. If you specify true, you must also set a maximum size in the size field. | |
timeseries.timeField | Required when creating a time series collection. The name of the field which contains the date in each time series document. Documents in a time series collection must have a valid BSON date as the value for the timeField. | |
timeseries.metaField |
Although the | |
timeseries.granularity |
Set For more information on granularity and bucket intervals, see Set Granularity for Time Series Data. | |
timeseries.bucketMaxSpanSeconds |
To downgrade below MongoDB 6.3, you must either modify the collection to use the corresponding | |
timeseries.bucketRoundingSeconds |
For example, setting both parameters to | |
expireAfterSeconds | ||
clusteredIndex |
Starting in MongoDB 5.3, you can create a collection with a clustered index. Clustered indexes are stored in the same WiredTiger file as the collection. The resulting collection is called a clustered collection. The
| |
changeStreamPreAndPostImages |
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):
To enable change stream pre- and post-images for the collection, set For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images. For a
| |
size | size field is required for capped collections and ignored for other collections. | |
max | size limit takes precedence over this limit. If a capped collection reaches the size limit before it reaches the maximum number of documents, MongoDB removes old documents. 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. | |
storageEngine |
Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection. The value of the
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. Starting in MongoDB 7.2, you can't specify For more information, see Specify Storage Engine Options. | |
validator |
The
| |
validationLevel |
| |
validationAction |
Validation of documents only applies to those documents as determined by the
| |
indexOptionDefaults |
The
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. | |
viewOn | 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 | |
pipeline | An array that consists of the aggregation pipeline stage(s). A view definition The view definition is public; i.e. See also | |
collation | Specifies the default collation for the collection or the view.
The collation option has the following syntax:
When specifying collation, the If you specify a collation at the collection level:
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. For a view, if no collation is specified, the view's default collation is the "simple" binary comparison collator. For a view on a collection, the view does not inherit the collection's collation settings. For a view on another view, the to be created view must specify the same collation settings. After you create the collection or the view, you cannot update its default collation. For an example that specifies the default collation during the creation of a collection, see Specify Collation. | |
writeConcern |
When issued on a sharded cluster, | |
encryptedFields |
To use encrypted fields in a collection, specify a new configuration option. You must have permissions to create and modify a collection to create or edit this configuration. The configuration includes a list of fields and their corresponding key identifiers, types, and supported queries.
For details, see Queryable Encryption Tutorials. | |
comment |
|
The db.createCollection() method and the db.createView() method wrap the create command.
Behavior行为
create has the following behavior:
Resource Locking
create 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 create releases the lock. create 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. This lock blocks creation or modification of views in the database until the command completes.
Transactions事务
You can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.
To use create in a transaction, the transaction must use read concern "local". If you specify a read concern level other than "local", the transaction fails.
Collection or View with Same Name and Options
If you run create with the same name and options as an existing collection or view, create returns success.
Stable API
Changed in version 5.0.在版本5.0中的更改。
When using Stable API V1, you cannot specify the following fields in a create command:
autoIndexIdcappedindexOptionDefaultsmaxsizestorageEngine
Access Control访问控制
If the deployment enforces authentication/authorization, create requires the following privileges:
| Task | Required Privileges |
|---|---|
| Create a non-capped collection |
|
| Create a capped collection |
|
| Create a view |
However, if the user has the |
A user with the readWrite built in role on the database has the required privileges to run the listed operations. Either create a user with the required role or grant the role to an existing user.
Examples示例
Create a Capped Collection
To create a capped collection limited to 64 kilobytes, issue the command in the following form:
db.runCommand( { create: "collection", capped: true, size: 64 * 1024 } )Create a Time Series Collection
To create a time series collection that captures weather data for the past 24 hours, issue this command:
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
}
)
Note
In this example expireAfterSeconds is specified as 86400 which means documents expire 86400 seconds after the timestamp value. See Set up Automatic Removal for Time Series Collections (TTL).
Create a Clustered Collection
The following create example adds a clustered collection named products:
db.runCommand( {
create: "products",
clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "products clustered key" }
} )
In the example, clusteredIndex specifies:
"key": { _id: 1 }, which sets the clustered index key to the_idfield."unique": true, which indicates the clustered index key value must be unique."name": "products 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):
- 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.
The following example creates a collection that has changeStreamPreAndPostImages enabled:
db.runCommand( {
create: "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.The following example sets
expireAfterSecondsto100seconds on an entire cluster:use admin
db.runCommand( {
setClusterParameter:
{ changeStreamOptions: {
preAndPostImages: { expireAfterSeconds: 100 }
} }
} )The following example returns the current
changeStreamOptionssettings, includingexpireAfterSeconds: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. 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
updateDescriptionare not large. - 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. 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. Areplaceevent always includes the post-image.replace事件。replace事件总是包括帖子图像。
- 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
- To request a pre-image, you set
fullDocumentBeforeChangetorequiredorwhenAvailableindb.collection.watch(). To request a post-image, you setfullDocumentusing the same method. Pre-images are written to the
config.system.preimagescollection.- The
config.system.preimagescollection may become large. To limit the collection size, you can setexpireAfterSecondstime for the pre-images as shown earlier. Pre-images are removed asynchronously by a background process.预图像由后台进程异步删除。
- The
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 collMod command before you can downgrade to an earlier MongoDB version.
Tip
- For change stream events and output, see Change Events.
- To watch a collection for changes, see
db.collection.watch(). - For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.
Create a View
Note
The view created by this command does not refer to materialized views. For discussion of on-demand materialized views, see $merge instead.
A view definition pipeline cannot include the $out or the $merge stage. This restriction also applies to embedded pipelines, such as pipelines used in $lookup or $facet stages.
To create a view using the create command, use the following syntax:
db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline> } )
or if specifying a collation:
db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline>, collation: <collation> } )
For example, create a 例如,使用以下文档创建survey collection with the following documents:survey集合:
db.survey.insertMany(
[
{ _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 managementRatings view with the _id, feedback.management, and department fields:
db.runCommand ( {
create: "managementFeedback",
viewOn: "survey",
pipeline: [ { $project: { "management": "$feedback.management", department: 1 } } ]
} )
Important
The view definition is public; i.e. 视图定义是公开的;即,db.getCollectionInfos() and explain operations on the view will include the pipeline that defines the view. As such, avoid referring directly to sensitive fields and values in view definitions.db.getCollectionInfos()和explain对视图的操作将包括定义视图的管道。因此,避免在视图定义中直接引用敏感字段和值。
Tip
Specify Collation指定排序规则
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.runCommand ( {
create: "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.runCommand( {
create: "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. See the WiredTiger documentation of collection level options for specific wiredTiger options.
Starting in MongoDB 7.2, you can't specify wiredTiger storage engine encryption options when you create a collection with db.createCollection(). To configure encryption for the WiredTiger storage engine, see Encryption at Rest.