Docs HomeMongoDB Manual

create

Definition定义

create

Explicitly creates a collection or view.显式创建集合或视图。

Note

The view created by this command does not refer to materialized views. 此命令创建的视图不引用物化视图。For discussion of on-demand materialized views, see $merge instead.有关按需物化视图的讨论,请参阅$merge

Syntax语法

The create command has the following syntax:create命令具有以下语法:

Note

MongoDB 6.3 adds the bucketMaxSpanSeconds and bucketRoundingSeconds parameters. MongoDB 6.3添加了bucketMaxSpanSecondsbucketRoundingSeconds参数。To downgrade below 6.3, you must either drop all collections with these parameters, or modify them to use the corresponding granularity, if possible. 若要降级到6.3以下,必须删除具有这些参数的所有集合,或者在可能的情况下修改它们以使用相应的granularityFor 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命令包含以下字段:

Field字段Type类型Description描述
createstringThe 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.如果您尝试创建一个已存在的集合或视图,并且为该现有集合或视图提供了相同的选项,则不会执行任何操作,并且返回成功。
cappedbooleanOptional.可选的。To create a capped collection, specify true. 若要创建封顶集合,请指定trueIf you specify true, you must also set a maximum size in the size field.如果指定true,则还必须在大小字段中设置最大大小。
timeseries.timeFieldstringRequired 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.metaFieldstringOptional.可选的。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. 指定字段的名称不能为_id,也不能与timeseries.timeField相同。The field can be of any type except array. 字段可以是除数组之外的任何类型。
timeseries.granularitystringOptional, do not use if setting bucketRoundingSeconds and bucketMaxSpanSeconds. 可选,如果设置了bucketRoundingSecondsbucketMaxSpanSeconds,则不要使用。Possible values are seconds (default), minutes, and hours.可能的值包括seconds(默认值)、minuteshours
Set granularity to the value that most closely matches the time between consecutive incoming timestamps. granularity设置为与连续传入时间戳之间的时间最匹配的值。This improves performance by optimizing how MongoDB internally stores data in the collection.这通过优化MongoDB在集合中内部存储数据的方式来提高性能。
For more information on granularity and bucket intervals, see Set Granularity for Time Series Data. 有关粒度和存储段间隔的更多信息,请参阅设置时间序列数据的粒度
timeseries.bucketMaxSpanSecondsintegerOptional, used with bucketRoundingSeconds as an alternative to granularity. 可选的,与bucketRoundingSeconds一起使用,作为粒度的替代方案。Sets the maximum time between timestamps in the same bucket. 设置同一桶中时间戳之间的最长时间。Possible values are 1-31536000. If you set bucketMaxSpanSeconds, you must set bucketRoundingSeconds to the same value.可能的值为1-31536000。如果设置了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.bucketRoundingSecondsintegerOptional, used with bucketMaxSpanSeconds as an alternative to granularity. 可选,与bucketMaxSpanSeconds一起使用,作为granularity的替代方案。Sets the number of seconds to round down by when MongoDB sets the minimum timestamp for a new bucket. 设置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-03-27T18:30:00Z
expireAfterSecondsintegerOptional.可选的。Specifies the seconds after which documents in a time series collection or clustered collection expire. MongoDB deletes expired documents automatically.指定时间序列集合聚集集合中的文档过期的秒数。MongoDB会自动删除过期文档。
clusteredIndexdocumentStarting in MongoDB 5.3, you can create a collection with a clustered index.从MongoDB 5.3开始,您可以创建一个具有聚集索引的集合。Collections created with a clustered index are called clustered collections.使用聚集索引创建的集合称为聚集集合。
See Clustered Collections.请参见聚集集合
clusteredIndex has the following syntax: 具有以下语法:
clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
Field字段Description描述
keyRequired.必要的。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字段的默认值是自动生成的唯一对象标识符,但您可以设置自己的聚集索引键值
uniqueRequired.必要的。Must be set to true. 必须设置为trueA 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.唯一索引表示集合不接受聚集索引键值与索引中现有值匹配的插入或更新文档。
nameOptional.可选的。A name that uniquely identifies the clustered index.唯一标识聚集索引的名称。

New in version 5.3. 5.3版新增。

changeStreamPreAndPostImagesdocumentOptional.可选的。
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>
}
enabledDescription描述
trueEnables change stream pre- and post-images for a collection.启用集合的更改流前映像和后映像。
falseDisables change stream pre- and post-images for a collection.禁用集合的更改流前映像和后映像。

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

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

New in version 6.0. 6.0版新增。

sizeintegerOptional.可选的。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字段对于封顶集合是必需的,而对于其他集合则被忽略。
maxintegerOptional.可选的。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限制足以包含最大数量的文档。
storageEnginedocumentOptional.可选的。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. 创建集合时指定的存储引擎配置将在复制期间进行验证并记录到操作日志中,以支持具有使用不同存储引擎的成员的复制副本集。
validatordocumentOptional.可选的。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除外。
Note
  • Validation occurs during updates and inserts. 在更新和插入期间进行验证。Existing documents do not undergo validation checks until modification.现有文件在修改前不会进行验证检查。
  • You cannot specify a validator for collections in the admin, local, and config databases.不能为admin数据库、local数据库和config数据库中的集合指定验证器。
  • You cannot specify a validator for system.* collections.不能为system.*集合指定验证器。
validationLevelstringOptional.可选的。Determines how strictly MongoDB applies the validation rules to existing documents during an update. 确定MongoDB在更新期间对现有文档应用验证规则的严格程度。
validationLevelDescription描述
"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.不要将规则应用于现有无效文档的更新。
validationActionstringOptional.可选的。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确定的那些文件。
validationActionDescription描述
"error"Default. 默认值。Documents must pass validation before the write occurs. Otherwise, the write operation fails.在写入之前,文档必须通过验证。否则,写入操作将失败。
"warn"Documents do not have to pass validation. If the document fails validation, the write operation logs the validation failure.文档不必通过验证。如果文档未通过验证,则写入操作会记录验证失败。
indexOptionDefaultsdocumentOptional.可选的。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. 创建索引时指定的存储引擎配置将在复制期间进行验证并记录到操作日志中,以支持具有使用不同存储引擎的成员的复制副本集。
viewOnstringThe 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. 该名称不是集合或视图的完整命名空间;ie.不包括数据库名称,并暗示与要创建的视图相同的数据库。You must create views in the same database as the source collection.您必须在与源集合相同的数据库中创建视图。
See also db.createView(). 另请参见db.createView()
pipelinearrayAn array that consists of the aggregation pipeline stage(s). 聚合管道阶段组成的数组。create creates the view by applying the specified pipeline to the viewOn collection or view.通过将指定的pipeline应用于viewOn集合或视图来创建视图。
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阶段中使用的管道。
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 db.createView(). 另请参见db.createView()
collationSpecifies the default collation for the collection or the view.指定集合或视图的默认排序规则
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选项具有以下语法:
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. 指定排序规则时,locale字段是必需的;所有其他排序规则字段都是可选的。For descriptions of the fields, see Collation Document.有关字段的说明,请参阅排序规则文档
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 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. 有关在创建集合期间指定默认排序规则的示例,请参阅指定排序规则
writeConcerndocumentOptional.可选的。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". 当在分片集群上发出时,mongoscreate命令及其助手db.createCollection()写入关注转换为"majority"
encryptedFieldsdocumentOptional.可选的。A document that configures queryable encryption for the collection being created.为正在创建的集合配置可查询加密的文档。
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. 配置包括字段及其相应的键标识符、类型和支持的查询的列表。
encryptedFieldsConfig = {
"fields": [
{
"keyId": UUID, // required
"path": String, // path to field, required
"bsonType": "string" | "int" ..., // required
"queries": // optional
[
{ "queryType": "equality" },
]
}
],
"queryPatterns": [ // optional
{"fieldName": queryType, "fieldName": queryType, … }
]
}
For details, see Quick Start. 有关详细信息,请参阅快速入门
commentanyOptional.可选的。
A user-provided comment to attach to this command. 要附加到此命令的用户提供的注释。Once set, this comment appears alongside records of this command in the following locations: 设置后,此注释将与此命令的记录一起显示在以下位置: A comment can be any valid BSON type (string, integer, object, array, etc). 注释可以是任何有效的BSON类型(字符串、整数、对象、数组等)。

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"以外的读取关注级别,则事务将失败。

Stable API

Changed in version 5.0.5.0版更改。

When using Stable API V1, you cannot specify the following fields in a create command:使用Stable API V1时,不能在创建命令中指定以下字段:

  • autoIndexId
  • capped
  • indexOptionDefaults
  • max
  • size
  • storageEngine

Access Control访问控制

If the deployment enforces authentication/authorization, create requires the following privileges:如果部署强制执行身份验证/授权,则create需要以下权限:

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.创建一个具有所需角色的用户,或者将该角色授予现有用户

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
}
)
Note

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 _id field.,将聚集索引键设置为_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 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.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 expireAfterSeconds to 100 seconds:以下示例将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使用默认的保留策略:保留前映像和后映像,直到从操作日志中删除相应的更改流事件。
    • 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.如果更改流事件从操作日志中删除,则相应的前映像和后映像也将被删除,而不管映像前和后映像的保留时间是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 updateDescription are 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 updateDescription are 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 replace change event. A replace event always includes the post-image.不要引起replace更改事件。replace事件始终包括后映像。
  • To request a pre-image, you set fullDocumentBeforeChange to required or whenAvailable in db.collection.watch(). 若要请求前映像,请在db.collection.watch()中将fullDocumentBeforeChange设置为requiredwhenAvailableTo request a post-image, you set fullDocument using the same method.若要请求后映像,请使用相同的方法设置fullDocument
  • Pre-images are written to the config.system.preimages collection.前映像将写入config.system.preimages集合。

    • The config.system.preimages collection may become large. config.system.preimages集合可能会变大。To limit the collection size, you can set expireAfterSeconds time for the pre-images as shown earlier.要限制集合大小,您可以为前映像设置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

See also: 另请参阅:

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.有关按需物化视图的讨论,请参阅$merge

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视图,其中包含_idfeedback.managementdepartment字段:

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. 视图定义是公开的;亦即db.getCollectionInfos()explain对视图的操作将包括定义视图的管道。As such, avoid referring directly to sensitive fields and values in view definitions.因此,请避免直接引用视图定义中的敏感字段和值。

Tip

See also: 另请参阅:

db.createView()

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文档