create
On this page本页内容
Definition定义
Syntax语法
The create command has the following syntax:create命令具有以下语法:
MongoDB 6.3 adds the MongoDB 6.3添加了bucketMaxSpanSeconds and bucketRoundingSeconds parameters. bucketMaxSpanSeconds和bucketRoundingSeconds参数。To downgrade below 6.3, you must either drop all collections with these parameters, or modify them to use the corresponding 若要降级到6.3以下,必须删除具有这些参数的所有集合,或者在可能的情况下修改它们以使用相应的granularity, if possible. granularity。For details see 有关详细信息,请参阅collMod.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 | string | |||||||||
capped | boolean | true. true。true, you must also set a maximum size in the size field.true,则还必须在大小字段中设置最大大小。 | ||||||||
timeseries.timeField | string | timeField.timeField的值。 | ||||||||
timeseries.metaField | string | _id or the same as the timeseries.timeField. _id,也不能与timeseries.timeField相同。 | ||||||||
timeseries.granularity | string | bucketRoundingSeconds and bucketMaxSpanSeconds. bucketRoundingSeconds和bucketMaxSpanSeconds,则不要使用。seconds (default), minutes, and hours.seconds(默认值)、minutes和hours。granularity to the value that most closely matches the time between consecutive incoming timestamps. granularity设置为与连续传入时间戳之间的时间最匹配的值。 | ||||||||
timeseries.bucketMaxSpanSeconds | integer | bucketRoundingSeconds as an alternative to granularity. bucketRoundingSeconds一起使用,作为粒度的替代方案。bucketMaxSpanSeconds, you must set bucketRoundingSeconds to the same value.bucketMaxSpanSeconds,则必须将bucketRoundingSeconds设置为相同的值。granularity value, or drop the collection. granularity,或者删除集合。collMod. collMod。 | ||||||||
timeseries.bucketRoundingSeconds | integer | bucketMaxSpanSeconds as an alternative to granularity. bucketMaxSpanSeconds一起使用,作为granularity的替代方案。bucketMaxSpanSecondsbucketMaxSpanSeconds1800 rounds new buckets down to the nearest 30 minutes. 1800会将新的桶循环到最接近的30分钟。2023-03-27T18:24:35Z does not fit an existing bucket, MongoDB creates a new bucket with a minimum time of 2023-03-27T18:00:00Z and a maximum time of 2023-03-27T18:30:00Z.2023-03-27T18:24:35Z的文档不适合现有桶,MongoDB会创建一个新桶,最小时间为2023-03-27T18:00:00Z,最大时间为2023-03-27T18:30:00Z。 | ||||||||
expireAfterSeconds | integer | |||||||||
clusteredIndex | document | clusteredIndexclusteredIndex: {
| ||||||||
changeStreamPreAndPostImages | document |
changeStreamPreAndPostImageschangeStreamPreAndPostImages: {
| ||||||||
size | integer | size field is required for capped collections and ignored for other collections.size字段对于封顶集合是必需的,而对于其他集合则被忽略。 | ||||||||
max | integer | 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 | storageEngine option should take the following form: storageEngine选项的值应采用以下形式:{ <storage-engine-name>: <options> }
Tip
| ||||||||
validator | document | validator option takes a document that specifies the validation rules or expressions. validator选项接受一个指定验证规则或表达式的文档。$near, $nearSphere, $text, and $where. $near、$nearSphere、$text和$where除外。Note
| ||||||||
validationLevel | string |
| ||||||||
validationAction | string | error on invalid documents or just warn about the violations but allow invalid documents to be inserted. Important validationLevel. validationLevel确定的那些文件。
| ||||||||
indexOptionDefaults | document | indexOptionDefaults option accepts a storageEngine document, which should take the following form: indexOptionDefaults选项接受storageEngine文档,该文档应采用以下形式:{ <storage-engine-name>: <options> }
| ||||||||
viewOn | string | db.createView(). db.createView()。 | ||||||||
pipeline | array | createpipeline to the viewOn collection or view.pipeline应用于viewOn集合或视图来创建视图。pipeline cannot include the $out or the $merge stage. pipeline不能包含$out或$merge阶段。$lookup or $facet stages.$lookup或$facet阶段中使用的管道。db.getCollectionInfos() and explain operations on the view will include the pipeline that defines the view. db.getCollectionInfos()和explain对视图的操作将包括定义视图的管道。db.createView(). db.createView()。 | ||||||||
collation | collationcollation选项具有以下语法:collation: {
locale field is mandatory; all other collation fields are optional. locale字段是必需的;所有其他排序规则字段都是可选的。
| |||||||||
writeConcern | document | mongos converts the write concern of the create command and its helper db.createCollection() to "majority". mongos将create命令及其助手db.createCollection()的写入关注转换为"majority"。 | ||||||||
encryptedFields | document | encryptedFieldsConfig = {
| ||||||||
comment | any |
|
The db.createCollection() method and the db.createView() method wrap the create command.db.createCollection()方法和db.createView()方法包装create命令。
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释放锁。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. system.views集合获取额外的独占锁。This lock blocks creation or modification of views in the database until the command completes.此锁会阻止在数据库中创建或修改视图,直到命令完成。
Transactions事务
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 若要在事务中使用create in a transaction, the transaction must use read concern "local". create,事务必须使用读取关注"local"。If you specify a read concern level other than 如果指定了"local", the transaction fails."local"以外的读取关注级别,则事务将失败。
See also: 另请参阅:
Stable API
Changed in version 5.0.5.0版更改。
When using Stable API V1, you cannot specify the following fields in a 使用Stable API V1时,不能在创建命令中指定以下字段:create command:
autoIndexIdcappedindexOptionDefaultsmaxsizestorageEngine
Access Control访问控制
If the deployment enforces authentication/authorization, 如果部署强制执行身份验证/授权,则create requires the following privileges:create需要以下权限:
createCollection on the database, orcreateCollection,或者insert on the collection to create insert | |
convertToCapped for the collectionconvertToCappedcreateCollection on the database createCollection | |
createCollection on the database.createCollection。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 Capped Collection创建封顶集合
To create a capped collection limited to 64 kilobytes, issue the command in the following form:要创建限制为64 KB的封顶集合,请按以下形式发出命令:
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:要创建捕捉过去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
}
)
In this example 在本例中,expireAfterSeconds is specified as 86400 which means documents expire 86400 seconds after the timestamp value. expireAfterSeconds被指定为86400,这意味着文档在timestamp值之后86400秒过期。See Set up Automatic Removal for Time Series Collections (TTL).请参阅为时间序列集合(TTL)设置自动删除。
Create a Clustered Collection创建群集集合
The following 以下create example adds a clustered collection named products:create示例添加了一个名为products的集群集合:
db.runCommand( {
create: "products",
clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "products 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": "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):从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.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.expireAfterSeconds中设置的前映和后映保留时间之后删除。The following example sets以下示例将expireAfterSecondsto100seconds: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使用默认的保留策略:保留前映像和后映像,直到从操作日志中删除相应的更改流事件。If a change stream event is removed from the oplog, then the corresponding pre- and post-images are also deleted regardless of the如果更改流事件从操作日志中删除,则相应的前映像和后映像也将被删除,而不管映像前和后映像的保留时间是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 megabytes. To limit the event size, you can:将更改流事件大小限制为小于16兆字节。要限制事件大小,您可以:Limit the document size to 8 megabytes.将文档大小限制为8兆字节。You can request pre- and post-images simultaneously in the change stream output if other change stream event fields like如果其他变更流事件字段(如updateDescriptionare not large.updateDescription)不大,则可以在变更流输出中同时请求前映像和后映像。Request only post-images in the change stream output for documents up to 16 megabytes 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 megabytes 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事件始终包括后映像。
To request a pre-image, you set若要请求前映像,请在fullDocumentBeforeChangetorequiredorwhenAvailableindb.collection.watch().db.collection.watch()中将fullDocumentBeforeChange设置为required或whenAvailable。To request a post-image, you set若要请求后映像,请使用相同的方法设置fullDocumentusing the same method.fullDocument。Pre-images are written to the前映像将写入config.system.preimagescollection.config.system.preimages集合。Theconfig.system.preimagescollection may become large.config.system.preimages集合可能会变大。To limit the collection size, you can set要限制集合大小,您可以为前映像设置expireAfterSecondstime for the pre-images as shown earlier.expireAfterSeconds时间,如前所示。Pre-images are removed asynchronously by a background process.前映像通过后台进程异步移除。
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版本。
See also: 另请参阅:
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.有关更改流输出的完整示例,请参阅文档前后映像的更改流。
Create a View创建视图
A view definition 视图定义pipeline cannot include the $out or the $merge stage. pipeline不能包含$out或$merge阶段。This restriction also applies to embedded pipelines, such as pipelines used in 此限制也适用于嵌入式管道,例如$lookup or $facet stages.$lookup或$facet阶段中使用的管道。
To create a view using the 要使用create command, use the following syntax:create命令创建视图,请使用以下语法:
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:managementRatings视图,其中包含_id、feedback.management和department字段:
db.runCommand ( {
create: "managementFeedback",
viewOn: "survey",
pipeline: [ { $project: { "management": "$feedback.management", department: 1 } } ]
} )
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: 另请参阅:
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(). 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. users的新集合,其中包含MongoDB将传递给wiredTiger存储引擎的特定配置字符串。See the WiredTiger documentation of collection level options有关特定的 for specific
wiredTiger options.WiredTiger选项,请参阅集合级别选项的WiredTinger文档。