Definition定义
collModcollModmakes it possible to add options to a collection or to modify view definitions.可以向集合添加选项或修改视图定义。Tip
In在mongosh, this command can also be run through thehideIndex()andunhideIndex()helper methods.mongosh中,此命令也可以通过hideIndex()和unhideIndex()的辅助方法运行。Helper methods are convenient for助手方法对mongoshusers, 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 bycollModdoes not refer to materialized views. For discussion of on-demand materialized views, see$mergeinstead.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>".
indexTheindexoption can change the following properties of an existing index:index选项可以更改现有索引的以下属性:Index Property索引属性Description描述expireAfterSecondsThe 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 forexpireAfterSecondsbefore.expireAfterSeconds的值,则返回expireAfterSeconds的旧值。
Modifying the index option修改索引选项expireAfterSecondsresets the$indexStatsfor 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 indexTTL索引expireAfterSecondsvalue must be within0and2147483647inclusive.expireAfterSeconds值必须在0和2147483647之间(包括0和21474647)。hiddenA boolean that determines whether the index is hidden or not from the query planner.一个布尔值,用于确定索引是否对查询计划器隐藏。If the如果hiddenvalue changes, the command returns a document that contains both the old and new values for the changed property:hidden_oldandhidden_new.hidden值更改,该命令将返回一个文档,其中包含更改后的属性hidden_old和hidden_new的旧值和新值。However, if the但是,如果hiddenvalue has not changed (i.e. hiding an already hidden index or unhiding an already unhidden index), the command omits thehidden_oldandhidden_newfields from the output.hidden值没有更改(即隐藏已隐藏的索引或取消隐藏已取消隐藏的索引),则该命令会从输出中省略hidden_old和hidden_new字段。To hide an index, you must have featureCompatibilityVersion set to要隐藏索引,必须将featureCompatibilityVersion设置为4.4或更高版本。4.4or greater.Modifying the index option如果值发生变化,修改hiddenresets the$indexStatsfor the index if the value changes.hidden的索引选项将重置索引的$indexStats。prepareUniqueA boolean that determines whether the index will accept new duplicate entries.一个布尔值,用于确定索引是否接受新的重复条目。New duplicate entries fail with DuplicateKey errors when当prepareUniqueistrue. The resulting index can be converted to a unique index.prepareUnique为true时,新的重复条目将失败,并出现DuplicateKey错误。生成的索引可以转换为唯一索引。To convert the index, use要转换索引,请使用带有collModwith theuniqueoption.unique选项的collMod。If an existing index is updated so that如果更新了现有索引,使prepareUniqueistrue, the index is not checked for pre-existing, duplicate index entries.prepareUnique为true,则不会检查索引中是否存在预先存在的重复索引条目。New in version 6.0.在版本6.0中新增。uniqueA boolean that determines whether the index is unique.一个布尔值,用于确定索引是否唯一。A value of不支持falseis not supported.false值。When当uniqueistrue,collModscans thekeyPatternindex for duplicates and then converts it to a unique index if there are no duplicate index entries.unique为true时,collMod会扫描keyPattern索引中的重复项,如果没有重复的索引条目,则将其转换为唯一索引。If duplicates are detected during the initial scan,如果在初始扫描期间检测到重复项,collModreturnsCannotConvertIndexToUniqueand a list of conflicting documents. To convert an index with duplicate entries to a unique index, correct any reported conflicts and reruncollMod.collMod将返回CannotConvertIndexToUnique和冲突文档列表。要将具有重复条目的索引转换为唯一索引,请更正所有报告的冲突,然后重新运行collMod。To end a conversion, set要结束转换,请将prepareUniquetofalse.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中新增。
dryRunDefault value:默认值:falseOnly used when仅在index.uniqueistrue.index.unique为true时使用。Before you convert a non-unique index to a unique index, you can run the在将非唯一索引转换为唯一索引之前,可以使用collModcommand withdryRun: true. If you do, MongoDB checks the collection for duplicate keys and returns any violations.dryRun:true运行collMod命令。如果你这样做,MongoDB会检查集合中是否有重复的键,并返回任何违规行为。Use使用dryRun: trueto confirm that you can convert an index to be unique without any errors.dryRun:true确认您可以将索引转换为唯一的,而不会出现任何错误。
Validate Documents验证文档
validatorvalidatorallows users to specify validation rules or expressions for a collection.允许用户为集合指定验证规则或表达式。Thevalidatoroption 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, andconfigdatabases.admin、admin和config数据库中的集合指定验证器。You cannot specify a validator for您不能为system.*collections.system.*集合指定验证器。
validationLevelThevalidationLeveldetermines 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的示例,请参阅为现有文档指定验证级别。
validationActionThevalidationActionoption determines whether toerroron invalid documents or justwarnabout 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
viewOnThe underlying source collection or view. The view definition is determined by applying the specified基础源代码集合或视图。视图定义是通过将指定的管道应用于此源来确定的。pipelineto this source.Required if modifying a view on a MongoDB deployment that is running with access control.如果修改使用访问控制运行的MongoDB部署上的视图,则需要此项。
pipelineThe aggregation pipeline that defines the view.定义视图的聚合管道。Note
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()andexplainoperations 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这与使用indexoption with theexpireAfterSecondsproperty 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要启用自动文档删除或修改时间序列集合的当前过期间隔,请更改expireAfterSecondsvalue:expireAfterSeconds值:db.runCommand( {
collMod: <collection>,
expireAfterSeconds: <number> | "off"
} )Set将expireAfterSecondsto"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)以指定文档过期的秒数。
granularityTo modify the granularity of a time series collection, you can increase要修改时间序列集合的粒度,您可以将timeseries.granularityfrom 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要更新自定义分桶字段bucketRoundingSecondsandbucketMaxSpanSecondsinstead ofgranularity, include both custom fields in thecollModcommand and set them to the same value:bucketRoundingSeconds和bucketMaxSpanSeconds而不是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如果任何时间序列集合明确指定了自定义分桶字段bucketMaxSpanSecondsandbucketRoundingSeconds.bucketMaxSpanSeconds和bucketRoundingSeconds,则无法降级到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, bothbucketMaxSpanSecondsandbucketRoundingSecondsmust be less than or equal to thegranularityequivalent:granularity值,bucketMaxSpanSeconds和bucketRoundingSeconds都必须小于或等于等效的粒度:granularitybucketRoundingSecondslimit (inclusive)限额(含)bucketMaxSpanSecondslimit (inclusive)限额(含)seconds60 3600 minutes3600 86400 hours86400 2592000
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 从MongoDB 6.0开始,您可以调整封顶集合的大小。要更改款项集合的最大大小(以字节为单位),请使用cappedSize option. 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 您不能使用这些命令来调整oplog的大小。请改用replSetResizeOplog instead.replSetResizeOplog。
cappedSizeSpecifies a new maximum size, in bytes, for a capped collection.为封顶集合指定新的最大大小(以字节为单位)。cappedSizemust be greater than0and less than1e+15(1 PB).cappedSize必须大于0且小于1e+15(1 PB)。
cappedMaxSpecifies a new maximum number of documents in a capped collection. Setting指定封顶集合中新的最大文档数。设置cappedMaxless than or equal to0implies 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使用changeStreamPreAndPostImagesfor a collection usingdb.createCollection(),create, orcollMod.db.createCollection()、create或collMod为集合启用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以下示例将整个集群上的expireAfterSecondsto100seconds on an entire cluster: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将使用默认保留策略:保留前后图像,直到从oplog中删除相应的更改流事件。If a change stream event is removed from the oplog, then the corresponding pre- and post-images are also deleted regardless of the如果从oplog中删除了更改流事件,则相应的预映像和后映像也将被删除,而不管映像保留时间为expireAfterSecondspre- and post-image retention time.expireAfterSeconds之前和之后。
Additional considerations:其他注意事项:
Enabling pre- and post-images consumes storage space and adds processing time. Only enable pre- and post-images if you need them.启用预映像和后映像会消耗存储空间并增加处理时间。仅在需要时启用前映像和后映像。Limit the change stream event size to less than 16 mebibytes. To limit the event size, you can:将更改流事件大小限制为小于16兆字节。要限制事件大小,您可以:Limit the document size to 8 megabytes. You can request pre- and post-images simultaneously in the change stream output if other change stream event fields like将文档大小限制为8 MB。如果其他更改流事件字段(如updateDescriptionare not large.updateDescription)不大,您可以在更改流输出中同时请求预映像和后映像。Request only post-images in the change stream output for documents up to 16 mebibytes if other change stream event fields like如果其他更改流事件字段(如updateDescriptionare not large.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不要引起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.preimagess集合。Theconfigsystempreimages集合可能会变大。要限制集合大小,您可以为预映像设置config.system.preimagescollection may become large. To limit the collection size, you can setexpireAfterSecondstime 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 从MongoDB 6.0开始,如果您将文档预映像和后映像用于更改流,则必须使用collMod command before you can downgrade to an earlier MongoDB version.collMod命令为每个集合禁用changeStreamPreAndPostImages,然后才能降级到早期的MongoDB版本。
Tip
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.有关更改流输出的完整示例,请参阅使用文档前后映像更改流。
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:您指定的注释将与此命令的记录一起显示在以下位置:
- mongod
log messages日志消息, in the,在attr.command.cursor.commentfield.attr.command.cursor.comment字段中。 Database profiler数据库分析器output, in the输出,在command.commentfield.command.comment字段中。currentOpoutput, in the输出,在command.commentfield.command.comment字段中。
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命令:
collMod | |
|
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_old和hidden_new字段。
To hide a text index, you must specify the index by 要隐藏文本索引,必须按name and not by keyPattern.name而不是按keyPattern指定索引。