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.Helper methods are convenient for
mongoshusers, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.Note
The view modified by this command does not refer to materialized views. For discussion of on-demand materialized views, see
$mergeinstead.
Compatibility
This command is available in deployments hosted in the following environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
The command has the following syntax:
Note
Starting in MongoDB 4.2
The
noPaddingandusePowerOf2SizesMMAPv1 options for thecollModcommand are removed.The view definition
pipelinecannot include the$outor the$mergestage. If the view definition includes nested pipeline (e.g. the view definition includes$lookupor$facetstage), this restriction applies to the nested pipelines as well.
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
Index Options
indexThe
indexoption can change the following properties of an existing index:Index PropertyDescriptionexpireAfterSecondsThe number of seconds that determines the expiration threshold of a TTL Collection.
If successful, the command returns a document that contains both the old and new values for the changed property:
expireAfterSeconds_oldandexpireAfterSeconds_new.You can only modify an existing TTL index; i.e. an index with an existing
expireAfterSecondsproperty. If the index does not have an existingexpireAfterSecondsproperty, the operation errors withno expireAfterSeconds field to update.Modifying the index option
expireAfterSecondsresets the$indexStatsfor the index.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.
The TTL index
expireAfterSecondsvalue must be within0and2147483647inclusive.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.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.To hide an index, you must have featureCompatibilityVersion set to
4.4or greater.Modifying the index option
hiddenresets the$indexStatsfor the index if the value changes.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 } } )
Document Validation
validatorNew in version 3.2.
validatorallows users to specify validation rules or expressions for a collection. For more information, see Schema Validation.The
validatoroption takes a document that specifies the validation rules or expressions. You can specify the expressions using the same operators as the query operators with the exception of$near,$nearSphere,$text, and$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.You cannot specify a validator for
system.*collections.
validationLevelNew in version 3.2.
The
validationLeveldetermines how strictly MongoDB applies the validation rules to existing documents during an update."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.
validationActionNew in version 3.2.
The
validationActionoption determines whether toerroron invalid documents or justwarnabout the violations but allow invalid documents.Important
Validation of documents only applies to those documents as determined by the
validationLevel."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.
Views
Note
The view modified by this command does not refer to materialized
views. For discussion of on-demand materialized views, see
$merge instead.
viewOnThe underlying source collection or view for the 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.
pipelineThe aggregation pipeline that defines the view.
Note
Required if modifying a view on a MongoDB deployment that is running with access control.
The view definition is public; i.e.
db.getCollectionInfos()andexplainoperations on the view will include the pipeline that defines the view. 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:
db.runCommand({ collMod: <collection>, expireAfterSeconds: <Number> || "off" })
The expireAfterSeconds field must be either:
A non-negative decimal number (
>=0)The string
"off".
A number specifies the number of seconds after which documents expire.
The string "off" removes the expireAfterSeconds parameter and
disables automatic removal.
Attach 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. The comment that you specify appears alongside records of this command in the following locations:
mongod log messages, in the
attr.command.cursor.commentfield.Database profiler output, in the
command.commentfield.currentOpoutput, in thecommand.commentfield.
Write Concern
Optional. A document expressing the write concern of the collMod command.
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:
Task | Required Privileges |
|---|---|
Modify a non-capped collection |
|
Modify a view |
The built-in role dbAdmin provides the required privileges.
Behavior
Resource Locking
The collMod command obtains a collection lock on
the specified collection for the duration of the operation.
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. 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).
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 5.0 or greater.
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.
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.
To hide a text index, you must specify the index by name and not by
keyPattern.
Add Document Validation to an Existing Collection
The following example adds a validator to an existing collection named
contacts.
Note
MongoDB 3.6 adds the $jsonSchema operator to support JSON
Schema validation.
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.
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.
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:
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.