collMod

On this page本页内容

Definition定义

collMod

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

Note注意

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

The command takes the following prototype form:该命令采用以下原型形式:

Note注意
Starting in MongoDB 4.2从MongoDB 4.2开始
  • MongoDB removes the MMAPv1 storage engine and the MMAPv1 specific options noPadding and usePowerOf2Sizes for collMod.MongoDB针对collMod删除了MMAPv1存储引擎和MMAPv2特定选项noPaddingusePowerOf2Sizes
  • The view definition pipeline cannot include the $out or the $merge stage. 视图定义pipeline不能包含$out$merge阶段。If the view definition includes nested pipeline (e.g. the view definition includes $lookup or $facet stage), this restriction applies to the nested pipelines as well.如果视图定义包含嵌套管道(例如,视图定义包含$lookup$facet阶段),则此限制也适用于嵌套管道。
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.对于<collection or view>,请指定当前数据库中的集合或视图的名称。

Options选项

Index Options索引选项

index

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

Index PropertyDescription描述
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的值,则为expireAofterSeconds的旧值。

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

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

New in version 4.4.在版本4.4中新增

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

db.runCommand( {
   collMod: <collection>,
   index: {
      keyPattern: <index_spec> || name: <index_name>,
      expireAfterSeconds: <number>,  // If changing the TTL expiration threshold
      hidden: <boolean>
              // If changing the visibility of the index from the query planner
   }
} )

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

Document Validation文档验证

validator

validator allows users to specify validation rules or expressions for a collection. 允许用户为集合指定验证规则或表达式For more information, see Schema Validation.有关详细信息,请参阅架构验证

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

The validationLevel determines how strictly MongoDB applies the validation rules to existing documents during an update.validationLevel确定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 validdocuments. 将验证规则应用于现有有效文档的插入和更新。Do not apply rules to updates on existing invaliddocuments.不要将规则应用于现有无效文档的更新。
validationAction

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

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.如果文档验证失败,则写入操作会记录验证失败。

To view the validation specifications for a collection, use the db.getCollectionInfos() method.要查看集合的验证规范,请使用db.getCollectionInfos()方法。

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 for the view. 视图的基础源集合或视图。The view definition is determined by applying the specified pipeline to this source.通过将指定的pipeline应用于此源来确定视图定义。

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注意

The view definition pipeline cannot include the $out or the $merge stage. 视图定义pipeline不能包含$out$merge阶段。If the view definition includes nested pipeline (e.g. the view definition includes $lookup or $facet stage), this restriction applies to the nested pipelines as well.如果视图定义包含嵌套管道(例如,视图定义包含$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} } ]
} )

Time Series Collections时间序列集合

To enable automatic removal of documents or change the expireAfterSeconds parameter value for an existing time series collection, issue the following collMod command:要启用自动删除文档或更改现有时间序列集合expireAfterSeconds参数值,请发出以下collMod命令:

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

The expireAfterSeconds field must be either:expireAfterSeconds字段必须是:

  • A non-negative decimal number (>=0)非负十进制数(>=0
  • The string "off".字符串"off"

A number specifies the number of seconds after which documents expire. 数字指定文档过期后的秒数。The string "off" removes the expireAfterSeconds parameter and disables automatic removal.字符串"off"删除expireAfterSeconds参数并禁用自动删除。

Write Concern写入关注点

Optional. 可选。A document expressing the write concern of the drop command.表示drop命令的写入问题的文档。

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数据库中的collMod
Modify a view修改视图

collMod in the database and either:在数据库中,或者:

  • no find on the view to modify, or在要修改的视图没有find,或
  • both find on the view to modify and find on the source collection/view.既可以在要修改的视图上find,也可以在源集合/视图上查找。

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

Behavior行为

Resource Locking资源锁定

The collMod command obtains an exclusive lock on the parent database of the specified collection for the duration of the operation. collMod命令在操作期间获取指定集合的父数据库上的独占锁。All subsequent operations on the database and all its collections must wait until collMod releases the lock.对数据库及其所有集合的所有后续操作必须等待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 4.4 or greater. 要隐藏索引,必须将featureCompatibilityVersion设置为4.4或更高。However, once hidden, the index remains hidden even with featureCompatibilityVersion set to 4.2 on MongoDB 4.4 binaries.然而,一旦隐藏,即使在MongoDB 4.4二进制文件上将featureCompatibilityVersion设置为4.2,索引也会保持隐藏状态。

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.具体地说,该操作在查询计划器中隐藏规范为{ 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 (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 a text index, you must specify the index by name and not by keyPattern.要隐藏文本索引,必须按name而不是按keyPattern指定索引。

Add Document Validation to an Existing Collection将文档验证添加到现有集合

The following example adds a validator to an existing collection named contacts.下面的示例将验证程序添加到名为contacts的现有集合中。

Note注意

MongoDB 3.6 adds the $jsonSchema operator to support JSON Schema validation.MongoDB 3.6添加了$jsonSchema运算符以支持JSON模式验证。

db.runCommand( { collMod: "contacts",
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "phone" ],
      properties: {
         phone: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         email: {
            bsonType : "string",
            pattern : "@mongodb\.com$",
            description: "must be a string and match the regular expression pattern"
         },
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "can only be one of the enum values"
         }
      }
   } },
   validationLevel: "moderate",
   validationAction: "warn"
} )

With the moderate validationLevel, MongoDB applies validation rules to insert operations and to update operationss to existing documents that already fulfill the validation criteria. 通过适度的validationLevel,MongoDB将验证规则应用于插入操作和更新已满足验证标准的现有文档的操作。Updates to existing documents that do not fulfill the validation criteria are not checked for validity.对不符合验证标准的现有文档的更新不会进行有效性检查。

With the warn validationAction, MongoDB logs any violations but allows the insertion or update to proceed.通过warnvalidationAction,MongoDB记录任何违规行为,但允许继续插入或更新。

For example, the following insert operation violates the validation rule.例如,以下插入操作违反了验证规则。

db.contacts.insertOne( { name: "Amanda", status: "Updated" } )

However, since the validationAction is warn only, MongoDB only logs the validation violation message and allows the operation to proceed:但是,由于validationAction仅为warn,MongoDB仅记录验证违规消息并允许操作继续:

2017-12-01T12:31:23.738-05:00 W STORAGE  [conn1] Document would fail validation collection: example.contacts doc: { _id: ObjectId('5a2191ebacbbfc2bdc4dcffc'), name: "Amanda", status: "Updated" }

For more information, see Schema Validation.有关详细信息,请参阅架构验证

←  cloneCollectionAsCappedcompact →