Database Manual / Reference / mongosh Methods / Databases

db.createCollection() (mongosh method方法)

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 db.createCollection() to create a:由于MongoDB在命令中首次引用集合时隐式创建集合,因此此方法主要用于创建使用特定选项的新集合。例如,您可以使用db.createCollection()创建一个:

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()方法具有以下参数:

Parameter参数Type类型Description描述
namestring字符串The name of the collection to create. See Naming Restrictions.要创建的集合的名称。请参见命名限制
optionsdocument文档

Optional. 可选。Configuration options for creating a:用于创建的配置选项:

  • Capped collection封顶集合
  • Clustered collection集群集合
  • View视图

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

Field字段Type类型Description描述
cappedboolean布尔值Optional. 可选。To create a capped collection, specify true. If you specify true, you must also set a maximum size in the size field.要创建封顶集合,请指定true。如果指定true,则还必须在size字段中设置最大大小。
timeseries.timeFieldstring字符串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.每个时间序列文档中包含日期的字段的名称。时间序列集合中的文档必须具有有效的BSON日期作为timeField的值。
timeseries.metaFieldstring字符串

Optional. 可选。The name of the field which contains metadata in each time series document. The metadata in the specified field should be data that is used to label a unique series of documents. The metadata should rarely, if ever, change.每个时间序列文档中包含元数据的字段的名称。指定字段中的元数据应该是用于标记一系列唯一文档的数据。元数据应该很少(如果有的话)发生变化。

The name of the specified field may not be _id or the same as the timeseries.timeField. The field can be of any type except array.指定字段的名称不能是_id,也不能与timeseries.timeField相同。字段可以是除数组之外的任何类型。

timeseries.granularitystring字符串

Optional, 可选。do not use if setting bucketRoundingSeconds and bucketMaxSpanSeconds. Possible values are seconds (default), minutes, and hours.如果设置bucketRoundingSecondsbucketMaxSpanSeconds,则不要使用。可能的值是seconds(默认值)、minuteshours

Set granularity to the value that most closely matches the time between consecutive incoming timestamps. This improves performance by optimizing how MongoDB internally stores data in the collection.granularity设置为与连续传入时间戳之间的时间最接近的值。这通过优化MongoDB在集合中内部存储数据的方式来提高性能。

For more information on granularity and bucket intervals, see Set Granularity for Time Series Data.有关粒度和桶间隔的更多信息,请参阅设置时间序列数据的粒度

timeseries.bucketMaxSpanSecondsinteger整数

Optional, 可选。used with bucketRoundingSeconds as an alternative to granularity. Sets the maximum time between timestamps in the same bucket. Possible values are 1-31536000. bucketRoundingSeconds一起使用,作为granularity的替代方案。设置同一桶中时间戳之间的最大时间间隔。可能的值为1-31536000。If you set bucketMaxSpanSeconds, you must set bucketRoundingSeconds to the same value.如果设置bucketMaxSpanSeconds,则必须将bucketRoundingSeconds设置为相同的值。

To downgrade below MongoDB 6.3, you must either modify the collection to use the corresponding granularity value, or drop the collection. 要降级到MongoDB 6.3以下,您必须修改集合以使用相应的granularity值,或者删除集合。For details, see collMod.有关详细信息,请参阅collMod

timeseries.bucketRoundingSecondsinteger整数

Optional, 可选。used with bucketMaxSpanSeconds as an alternative to granularity. Sets the number of seconds to round down by when MongoDB sets the minimum timestamp for a new bucket. bucketMaxSpanSeconds一起使用,作为granularity的替代方案。设置MongoDB为新桶设置最小时间戳时四舍五入的秒数。Must be equal to bucketMaxSpanSeconds.必须等于bucketMaxSpanSeconds

For example, setting both parameters to 1800 rounds new buckets down to the nearest 30 minutes. 例如,将这两个参数都设置为1800,将新桶四舍五入到最接近的30分钟。If a document with a time of 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-103-27T18:30:00Z的新桶。

expireAfterSecondsnumber数字

Optional. 可选。Specifies the seconds after which documents in a time series collection or clustered collection expire. MongoDB deletes expired documents automatically.指定时间序列集合群集集合中的文档过期的秒数。MongoDB会自动删除过期的文档。

For clustered collections, the documents are deleted automatically based on the clustered index key _id and the values must be date types. See TTL Indexes.对于聚集集合,文档将根据聚集索引键_id自动删除,并且值必须是日期类型。请参阅TTL索引

clusteredIndexdocument文档

Starting in MongoDB 5.3, you can create a collection with a clustered index. 从MongoDB 5.3开始,您可以创建一个具有聚集索引的集合。Clustered indexes are stored in the same WiredTiger file as the collection. 聚集索引与集合存储在同一个WiredTiger文件中。The resulting collection is called a clustered collection.生成的集合称为集群集合

The clusteredIndex field has the following syntax:clusteredIndex字段具有以下语法:

clusteredIndex: {
key: <object>,
unique: <boolean>,
name: <string>
}
key
Required. The clustered index key field. Must be set to { _id: 1 }. 必修的。聚集索引键字段。必须设置为{ _id: 1 }The default value for the _id field is an automatically generated unique object identifier, but you can set your own clustered index key values._id字段的默认值是自动生成的唯一对象标识符,但您可以设置自己的聚集索引键值
unique
Required. Must be set to true. A unique index indicates the collection will not accept inserted or updated documents where the clustered index key value matches an existing value in the index.必修的。必须设置为true。唯一索引表示集合将不接受聚集索引键值与索引中现有值匹配的插入或更新文档。
name
Optional. A name that uniquely identifies the clustered index.可选。唯一标识聚集索引的名称。

New in version 5.3.在版本5.3中新增。

changeStreamPreAndPostImagesdocument文档

Optional.可选。

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 changeStreamPreAndPostImages for a collection using db.createCollection(), create, or collMod.使用db.createCollection()createcollMod为集合启用changeStreamPreAndPostImages

changeStreamPreAndPostImages has the following syntax:具有以下语法:

changeStreamPreAndPostImages: {
enabled: <boolean>
}

To enable change stream pre- and post-images for the collection, set enabled to true.要为集合启用更改流前映像和后映像,请将enabled设置为true

For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.有关更改流输出的完整示例,请参阅使用文档前后映像更改流

For a db.createCollection() example on this page, see Create a Collection with Change Stream Pre- and Post-Images for Documents.有关此页面上的db.createCollection()示例,请参阅使用更改流为文档创建前后映像的集合

New in version 6.0.在版本6.0中新增。

sizenumber数字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字段对于有上限的集合是必需的,对于其他集合则忽略。
maxnumber数字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限制足以包含最大数量的文档。
storageEnginedocument文档

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中,以支持使用不同存储引擎的成员的副本集。

Starting in MongoDB 7.2, you can't specify wiredTiger storage engine encryption options when you create a collection with db.createCollection(). 从MongoDB 7.2开始,当您使用db.createCollection()创建集合时,您不能指定wiredTiger存储引擎加密选项。To configure encryption for the WiredTiger storage engine, see Encryption at Rest.要为WiredTiger存储引擎配置加密,请参阅静态加密

For details, see Specify Storage Engine Options.有关详细信息,请参阅指定存储引擎选项

validatordocument文档

Optional. 可选。Allows users to specify validation rules or expressions for the collection.允许用户为集合指定验证规则或表达式

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 $near, $nearSphere, $text, and $where.您可以使用与查询运算符相同的运算符指定表达式,但$near$nearSphere$text$where除外。

To learn how to create a collection with schema validation, see Specify JSON Schema Validation.要了解如何使用模式验证创建集合,请参阅指定JSON模式验证

validationLevelstring字符串

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

"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.将验证规则应用于现有有效文档的插入和更新。不要对现有无效文档的更新应用规则。

To see an example that uses validationLevel, see Specify Validation Level for Existing Documents.要查看使用validationLevel的示例,请参阅为现有文档指定验证级别

validationActionstring字符串

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

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

To see an example that uses validationAction, see Choose How to Handle Invalid Documents.要查看使用validationAction的示例,请参阅选择如何处理无效文档

indexOptionDefaultsdocument文档

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中,以支持使用不同存储引擎的成员的副本集。

viewOnstring字符串The name of the source collection or view from which to create a view. For details, see db.createView().要从中创建视图的源集合或视图的名称。有关详细信息,请参阅db.createView()
pipelinearray数组An array that consists of the aggregation pipeline stage(s). 聚合管道阶段组成的数组。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()
collationdocument文档

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

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.例如,请参阅指定排序规则

writeConcerndocument文档

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()需要以下权限:

Task任务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集合上的convertToCapped以及

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行为

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 _id field.,它将聚集索引键设置为_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 changeStreamPreAndPostImages for a collection using db.createCollection(), create, or collMod.使用db.createCollection()createcollMod为集合启用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 expireAfterSeconds to 100 seconds on an entire cluster:以下示例将整个集群上的expireAfterSeconds设置为100秒:

      use admin
      db.runCommand( {
      setClusterParameter:
      { changeStreamOptions: {
      preAndPostImages: { expireAfterSeconds: 100 }
      } }
      } )
    • The following example returns the current changeStreamOptions settings, including expireAfterSeconds:以下示例返回当前changeStreamOptions设置,包括expireAfterSeconds

      db.adminCommand( { getClusterParameter: "changeStreamOptions" } )
    • Setting expireAfterSeconds to off uses 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 expireAfterSeconds pre- and post-image retention time.如果从oplog中删除了更改流事件,则相应的前映像和后映像也将被删除,而不管映像保留时间为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 updateDescription are not large.将文档大小限制为8 MB。如果其他更改流事件字段(如updateDescription)不大,您可以在更改流输出中同时请求前映像和后映像。
    • Request only post-images in the change stream output for documents up to 16 mebibytes if other change stream event fields like updateDescription are 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 replace change event. 不要引起replace更换事件。A replace event always includes the post-image.replace事件总是包括后映像。
  • To request a pre-image, you set fullDocumentBeforeChange to required or whenAvailable in db.collection.watch(). To request a post-image, you set fullDocument using the same method.要请求前映像,您可以在db.collection.watch()中将fullDocumentBeforeChange设置为requiredwhenAvailable。要请求后映像,您可以使用相同的方法设置fullDocument
  • Pre-images are written to the config.system.preimages collection.前映像会写入config.system.preimages集合。

    • The config.system.preimages collection may become large. To limit the collection size, you can set expireAfterSeconds time 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 collMod command before you can downgrade to an earlier MongoDB version.从MongoDB 6.0开始,如果您将文档前映像和后映像用于更改流,则必须使用collMod命令为每个集合禁用changeStreamPreAndPostImages,然后才能降级到早期的MongoDB版本。

Tip

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 wiredTiger storage engine encryption options when you create a collection with db.createCollection(). 从MongoDB 7.2开始,当您使用db.createCollection()创建集合时,您不能指定wiredTiger存储引擎加密选项。To configure encryption for the WiredTiger storage engine, see Encryption at Rest.要为WiredTiger存储引擎配置加密,请参阅静态加密