Database Manual / Reference / Database Commands / Administration

collMod (database command数据库命令)

Definition定义

collMod

collMod makes it possible to add options to a collection or to modify view definitions.可以向集合添加选项或修改视图定义。

Tip

In mongosh, this command can also be run through the hideIndex() and unhideIndex() helper methods.mongosh中,此命令也可以通过hideIndex()unhideIndex()的辅助方法运行。

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. 助手方法对mongosh用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。In cases where the convenience is not needed or the additional return fields are required, use the database command.如果不需要便利性或需要额外的返回字段,请使用数据库命令。

Note

The view modified by collMod does not refer to materialized views. For discussion of on-demand materialized views, see $merge instead.collMod修改的视图不引用物化视图。有关按需物化视图的讨论,请参阅$merge

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 command has the following syntax:该命令具有以下语法:

db.runCommand(
{
collMod: <collection or view>,
<option1>: <value1>,
<option2>: <value2>,
...
}
)

For the <collection or view>, specify the name of a collection or view in the current database.对于<集合或视图>,指定当前数据库中集合或视图的名称。

Options选项

Change Index Properties更改索引属性

To change index options, specify either the key pattern or name of the existing index options you want to change:要更改索引选项,请指定要更改的现有索引选项的键模式或名称:

db.runCommand( {
collMod: <collection>,
index: {
keyPattern: <index_spec> | name: <index_name>,
expireAfterSeconds: <number>, // Set the TTL expiration threshold
hidden: <boolean>, // Change index visibility in the query planner
prepareUnique: <boolean>, // Reject new duplicate index entries
unique: <boolean> // Convert an index to a unique index
},
dryRun: <boolean>
} )

If the index does not exist, the command errors with the message 如果索引不存在,则命令将显示错误消息"cannot find index <name|keyPattern> for ns <db.collection>".

index

The index option can change the following properties of an existing index:index选项可以更改现有索引的以下属性:

Index Property索引属性Description描述
expireAfterSeconds

The number of seconds that determines the expiration threshold of a TTL Collection.确定TTL集合过期阈值的秒数。

If successful, the command returns a document that contains:如果成功,该命令将返回一个文档,其中包含:

  • expireAfterSeconds_new, the new value for expireAfterSecondsexpireAfterSeconds的新值
  • expireAfterSeconds_old, the old value for expireAfterSeconds, if the index had a value for expireAfterSeconds before.,如果索引之前有expireAfterSeconds的值,则返回expireAfterSeconds的旧值。

Modifying the index option expireAfterSeconds resets the $indexStats for the index.修改索引选项expireAfterSeconds会重置索引的$indexStats

If you use TTL indexes created before MongoDB 5.0, or if you want to sync data created in MongDB 5.0 with a pre-5.0 installation, see Indexes Configured Using NaN to avoid misconfiguration issues.如果您使用MongoDB 5.0之前创建的TTL索引,或者如果您想将MongDB 5.0中创建的数据与5.0之前的安装同步,请参阅使用NaN配置的索引以避免配置错误问题。

The TTL index expireAfterSeconds value must be within 0 and 2147483647 inclusive.TTL索引expireAfterSeconds值必须在02147483647之间(包括021474647)。

hidden

A boolean that determines whether the index is hidden or not from the query planner.一个布尔值,用于确定索引是否对查询计划器隐藏

If the hidden value changes, the command returns a document that contains both the old and new values for the changed property: hidden_old and hidden_new.如果hidden值更改,该命令将返回一个文档,其中包含更改后的属性hidden_oldhidden_new的旧值和新值。

However, if the hidden value has not changed (i.e. hiding an already hidden index or unhiding an already unhidden index), the command omits the hidden_old and hidden_new fields from the output.但是,如果hidden值没有更改(即隐藏已隐藏的索引或取消隐藏已取消隐藏的索引),则该命令会从输出中省略hidden_oldhidden_new字段。

To hide an index, you must have featureCompatibilityVersion set to 4.4 or greater.要隐藏索引,必须将featureCompatibilityVersion设置为4.4或更高版本。

Modifying the index option hidden resets the $indexStats for the index if the value changes.如果值发生变化,修改hidden的索引选项将重置索引的$indexStats

prepareUnique

A boolean that determines whether the index will accept new duplicate entries.一个布尔值,用于确定索引是否接受新的重复条目。

New duplicate entries fail with DuplicateKey errors when prepareUnique is true. The resulting index can be converted to a unique index. prepareUniquetrue时,新的重复条目将失败,并出现DuplicateKey错误。生成的索引可以转换为唯一索引。To convert the index, use collMod with the unique option.要转换索引,请使用带有unique选项的collMod

If an existing index is updated so that prepareUnique is true, the index is not checked for pre-existing, duplicate index entries.如果更新了现有索引,使prepareUniquetrue,则不会检查索引中是否存在预先存在的重复索引条目。

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

unique

A boolean that determines whether the index is unique.一个布尔值,用于确定索引是否唯一。

A value of false is not supported.不支持false值。

When unique is true, collMod scans the keyPattern index for duplicates and then converts it to a unique index if there are no duplicate index entries.uniquetrue时,collMod会扫描keyPattern索引中的重复项,如果没有重复的索引条目,则将其转换为唯一索引。

If duplicates are detected during the initial scan, collMod returns CannotConvertIndexToUnique and a list of conflicting documents. To convert an index with duplicate entries to a unique index, correct any reported conflicts and rerun collMod.如果在初始扫描期间检测到重复项,collMod将返回CannotConvertIndexToUnique和冲突文档列表。要将具有重复条目的索引转换为唯一索引,请更正所有报告的冲突,然后重新运行collMod

To end a conversion, set prepareUnique to false.要结束转换,请将prepareUnique设置为false

To see an example of how to convert a non-unique index to a unique index, see Convert an Existing Index to a Unique Index.要查看如何将非唯一索引转换为唯一索引的示例,请参阅将现有索引转换为唯一索引

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

dryRun

Default value: 默认值:false

Only used when index.unique is true.仅在index.uniquetrue时使用。

Before you convert a non-unique index to a unique index, you can run the collMod command with dryRun: true. If you do, MongoDB checks the collection for duplicate keys and returns any violations.在将非唯一索引转换为唯一索引之前,可以使用dryRun:true运行collMod命令。如果你这样做,MongoDB会检查集合中是否有重复的键,并返回任何违规行为。

Use dryRun: true to confirm that you can convert an index to be unique without any errors.使用dryRun:true确认您可以将索引转换为唯一的,而不会出现任何错误。

Validate Documents验证文档

validator

validator allows users to specify validation rules or expressions for a 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.您不能为adminadminconfig数据库中的集合指定验证器。
  • You cannot specify a validator for system.* collections.您不能为system.*集合指定验证器。
validationLevel

The validationLevel determines how strictly MongoDB applies the validation rules to existing documents during an update.validationLevel决定了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的示例,请参阅为现有文档指定验证级别

validationAction

The validationAction option determines whether to error on invalid documents or just warn about the violations but allow invalid documents.validationAction选项决定是在无效文档上出错,还是只是警告违规但允许无效文档。

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的示例,请参阅选择如何处理无效文档

Modify Views修改视图

Note

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

viewOn

The underlying source collection or view. The view definition is determined by applying the specified pipeline to this source.基础源代码集合或视图。视图定义是通过将指定的管道应用于此源来确定的。

Required if modifying a view on a MongoDB deployment that is running with access control.如果修改使用访问控制运行的MongoDB部署上的视图,则需要此项。

pipeline

The aggregation pipeline that defines the view.定义视图聚合管道

Note

A view definition pipeline cannot include the $out or the $merge stage. 视图定义管道不能包含$out$merge阶段。This restriction also applies to embedded pipelines, such as pipelines used in $lookup or $facet stages.此限制也适用于嵌入式管道,例如$lookup$facet阶段中使用的管道。

Required if modifying a view on a MongoDB deployment that is running with access control.如果修改使用访问控制运行的MongoDB部署上的视图,则需要此项。

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.因此,避免在视图定义中直接引用敏感字段和值。

db.runCommand( {
collMod: "myView",
viewOn: "activities",
pipeline: [
{ $match: { status: "Q" } },
{ $project: { user: 1, date: 1, description: 1} } ]
} )

Modify Time Series Collections修改时间序列集合

expireAfterSeconds

Note

This is distinct from using the index option with the expireAfterSeconds property to change the expiration time for a TTL Collection.这与使用expireAfterSeconds属性的index选项更改TTL集合的过期时间不同。

To enable automatic document removal or modify the current expiration interval for a time series collection, change the expireAfterSeconds value:要启用自动文档删除或修改时间序列集合的当前过期间隔,请更改expireAfterSeconds值:

db.runCommand( {
collMod: <collection>,
expireAfterSeconds: <number> | "off"
} )

Set expireAfterSeconds to "off" to disable automatic removal, or a non-negative decimal number (>=0) to specify the number of seconds after which documents expire.expireAfterSeconds设置为"off"以禁用自动删除,或设置非负十进制数(>=0)以指定文档过期的秒数。

granularity

To modify the granularity of a time series collection, you can increase timeseries.granularity from a shorter unit of time to a longer one:要修改时间序列集合的粒度,您可以将timeseries.granularity从较短的时间单位增加到较长的时间单位:

db.runCommand( {
collMod: "weather24h",
timeseries: { granularity: "seconds" | "minutes" | "hours" }
} )

To update the custom bucketing fields bucketRoundingSeconds and bucketMaxSpanSeconds instead of granularity, include both custom fields in the collMod command and set them to the same value:要更新自定义分桶字段bucketRoundingSecondsbucketMaxSpanSeconds而不是granularity,请在collMod命令中包含这两个自定义字段并将其设置为相同的值:

db.runCommand( {
collMod: "weather24h",
timeseries: {
bucketRoundingSeconds: 86400,
bucketMaxSpanSeconds: 86400
}
} )

You cannot decrease the granularity interval or the custom bucketing values.您不能减小粒度间隔或自定义bucketing值。

Important

You cannot downgrade below MongoDB 6.3 if any time series collections explicitly specify the custom bucketing fields bucketMaxSpanSeconds and bucketRoundingSeconds. 如果任何时间序列集合明确指定了自定义分桶字段bucketMaxSpanSecondsbucketRoundingSeconds,则无法降级到MongoDB 6.3以下。If possible, convert to the corresponding granularity. If you cannot, you must drop the collection before downgrading.如果可能,转换为相应的granularity。如果不能,则必须在降级之前删除集合。

To convert a collection from custom bucketing to a granularity, value, both bucketMaxSpanSeconds and bucketRoundingSeconds must be less than or equal to the granularity equivalent:要将集合从自定义分桶转换为granularity值,bucketMaxSpanSecondsbucketRoundingSeconds都必须小于或等于等效的粒度:

granularitybucketRoundingSeconds limit (inclusive)限额(含)bucketMaxSpanSeconds limit (inclusive)限额(含)
seconds603600
minutes360086400
hours864002592000

Resize a Capped Collection调整封顶集合的大小

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

Starting in MongoDB 6.0, you can resize a capped collection. To change a capped collection's maximum size in bytes, use the cappedSize option. 从MongoDB 6.0开始,您可以调整封顶集合的大小。要更改款项集合的最大大小(以字节为单位),请使用cappedSize选项。To change the maximum number of documents in an existing capped collection, use the cappedMax option.要更改现有封顶集合中的最大文档数,请使用cappedMax选项。

Note

You can't use these commands to resize the oplog. Use replSetResizeOplog instead.您不能使用这些命令来调整oplog的大小。请改用replSetResizeOplog

cappedSize
Specifies a new maximum size, in bytes, for a capped collection. cappedSize must be greater than 0 and less than 1e+15 (1 PB).为封顶集合指定新的最大大小(以字节为单位)。cappedSize必须大于0且小于1e+15(1 PB)。
cappedMax
Specifies a new maximum number of documents in a capped collection. Setting cappedMax less than or equal to 0 implies no limit.指定封顶集合中新的最大文档数。设置cappedMax小于或等于0意味着没有限制。

For example, the following command sets the maximum size of a capped collection to 100000 bytes and sets the maximum number of documents in the collection to 500:例如,以下命令将封顶集合的最大大小设置为100000字节,并将集合中的最大文档数设置为500:

db.runCommand( {
collMod: <collection>,
cappedSize: 100000,
cappedMax: 500
} )

Change Streams with Document Pre- and Post-Images使用文档前后映像更改流

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

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):从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

To use collMod to enable change stream pre- and post-images for a collection, use the changeStreamPreAndPostImages field:要使用collMod启用集合的更改流前映和后映像,请使用changeStreamPreAndPostImages字段:

db.runCommand( {
collMod: <collection>,
changeStreamPreAndPostImages: { enabled: <boolean> }
} )

To enable change stream pre- and post-images for a collection, set changeStreamPreAndPostImages to true. For example:要为集合启用更改流预映像和后映像,请将changeStreamPreAndPostImages设置为true。例如:

db.runCommand( {
collMod: "orders",
changeStreamPreAndPostImages: { enabled: true }
} )

To disable change stream pre- and post-images for a collection, set changeStreamPreAndPostImages to false. For example:要禁用集合的更改流前映和后映像,请将changeStreamPreAndPostImages设置为false。例如:

db.runCommand( {
collMod: "orders",
changeStreamPreAndPostImages: { enabled: false }
} )

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. 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.preimagess集合。

    • 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.configsystempreimages集合可能会变大。要限制集合大小,您可以为预映像设置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

Attach Comment附上评论

comment

Optional. 可选。You can attach a comment to this command. The comment must be a top-level field and can be any valid BSON type. 您可以为此命令附加注释。注释必须是顶级字段,可以是任何有效的BSON类型The comment that you specify appears alongside records of this command in the following locations:您指定的注释将与此命令的记录一起显示在以下位置:

Write Concern写入关注

w

Optional. 可选。A document expressing the write concern of the collMod command.表示collMod命令写入关注的文档。

Omit to use the default write concern.省略使用默认写入关注。

Access Control访问控制

If the deployment enforces authentication/authorization, you must have the following privilege to run the collMod command:如果部署强制执行身份验证/授权,则必须具有以下权限才能运行collMod命令:

Task任务Required Privileges所需权限
Modify a non-capped collection修改非封顶集合collMod in the database在数据库中
Modify a view修改视图

collMod in the database and either:在数据库中输入collMod,然后执行以下任一操作:

  • no find on the view to modify, or在视图中找不到要修改的内容,或
  • both find on the view to modify and find on the source collection/view.在视图上查找以进行修改,在源代码集合/视图上查找。

The built-in role dbAdmin provides the required privileges.内置角色dbAdmin提供所需的权限。

Behavior行为

Resource Locking资源锁定

The collMod command obtains a collection lock on the specified collection for the duration of the operation.collMod命令在操作期间获取指定集合的集合锁。

Examples示例

Change Expiration Value for Indexes更改索引的过期值

The following example updates the expireAfterSeconds property of an existing TTL index { lastAccess: 1 } on a collection named user_log. 以下示例更新了名为user_log的集合上现有TTL索引{ lastAccess: 1 }expireAfterSeconds属性。The current expireAfterSeconds property for the index is set to 1800 seconds (or 30 minutes) and the example changes the value to 3600 seconds (or 60 minutes).索引的当前expireAfterSeconds属性设置为1800秒(或30分钟),示例将该值更改为3600秒(或60分钟)。

db.runCommand({
collMod: "user_log",
index: {
keyPattern: { lastAccess: 1 },
expireAfterSeconds: 3600
}
})

If successful, the operation returns a document that includes both the old and new value for the changed property:如果成功,操作将返回一个文档,其中包含更改属性的新旧值:

{ "expireAfterSeconds_old" : 1800, "expireAfterSeconds_new" : 3600, "ok" : 1 }

Hide an Index from the Query Planner在查询计划器中隐藏索引

Note

To hide an index, you must have featureCompatibilityVersion set to 6.0 or greater.要隐藏索引,必须将featureCompatibilityVersion设置为6.0或更高版本。

The following example hides an existing index on the orders collection. Specifically, the operation hides the index with the specification { shippedDate: 1 } from the query planner.以下示例隐藏orders集合上的现有索引。具体来说,该操作对查询计划器隐藏了规范为{shippedDate:1}的索引。

db.runCommand( {
collMod: "orders",
index: {
keyPattern: { shippedDate: 1 },
hidden: true
}
} )

If successful, the operation returns a document that includes both the old and new value for the changed property:如果成功,操作将返回一个文档,其中包含更改属性的新旧值:

{ "hidden_old" : false, "hidden_new" : true, "ok" : 1 }

Note

If the operation is successful but the hidden value has not changed (specifically, hiding an already hidden index or unhiding an already unhidden index), the command omits the hidden_old and hidden_new fields from the output.如果操作成功,但hidden值没有更改(具体来说,隐藏已隐藏的索引或取消隐藏已取消隐藏的索引),则该命令会从输出中省略hidden_oldhidden_new字段。

To hide a text index, you must specify the index by name and not by keyPattern.要隐藏文本索引,必须按name而不是按keyPattern指定索引。