Navigation
This version of the documentation is archived and no longer supported.

collMod

Definition

collMod

collMod makes it possible to add options to a collection or to modify view definitions.

Tip

In the mongo Shell, this command can also be run through the hideIndex and unhideIndex helper methods.

Helper methods are convenient for mongo users, 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 $merge instead.

The command takes the following prototype form:

Starting in MongoDB 4.2

  • The noPadding and usePowerOf2Sizes MMAPv1 options for the collMod command are removed. Do not use those options because upgrading from MongoDB 4.0 to 4.2 causes the 4.2 secondary members to immediately halt.
  • The view definition pipeline cannot include the $out or the $merge stage. 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.
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.

Use the userFlags field in the db.collection.stats() output to check the options enabled for a collection.

Options

TTL Collections

index

The index option changes the expiration time of a TTL Collection.

Specify the key or index name, and new expiration time with a document of the form:

{keyPattern: <index_spec> || name: <index_name>, expireAfterSeconds: <seconds> }

In this example, <index_spec> is an existing index in the collection. In cases of multiple indexes with the same key pattern, the user is required to specify the index by name. seconds is the number of seconds to subtract from the current time.

On success collMod returns a document with fields expireAfterSeconds_old and expireAfterSeconds_new set to their respective values.

On failure, collMod returns a document with no expireAfterSeconds field to update if there is no existing expireAfterSeconds field or cannot find index { **key**: 1.0 } for ns **namespace** if the specified keyPattern does not exist.

Document Validation

validator

New in version 3.2.

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. You can specify the expressions using the same operators as the query operators with the exception of : $geoNear, $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, and config databases.
  • You cannot specify a validator for system.* collections.
validationLevel

New in version 3.2.

The validationLevel determines how strictly MongoDB applies the validation rules to existing documents during an update.

validationLevel Description
"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.
validationAction

New in version 3.2.

The validationAction option determines whether to error on invalid documents or just warn about the violations but allow invalid documents.

Important

Validation of documents only applies to those documents as determined by the validationLevel.

validationAction Description
"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.

viewOn

The underlying source collection or view for the 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.

pipeline

The aggregation pipeline that defines the view.

Note

The view definition pipeline cannot include the $out or the $merge stage. 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.

Required if modifying a view on a MongoDB deployment that is running with access control.

The view definition is public; i.e. db.getCollectionInfos() and explain operations 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} } ]
} )

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:

  Required Privileges
Modify a non-capped collection collMod in the database
Modify a view

collMod in the database and either:

  • 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.

Behavior

Resource Locking

The collMod command obtains an exclusive lock on the parent database of the specified collection for the duration of the operation. All subsequent operations on the database and all its collections must wait until collMod releases the lock.

Examples

Change Expiration Value for Indexes

To update the expiration value for a collection named sessions indexed on a lastAccess field from 30 minutes to 60 minutes, use the following operation:

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

Which will return the document:

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

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.insert( { 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-0500 W STORAGE  [conn1] Document would fail validation collection: example.contacts doc: { _id: ObjectId('5a2191ebacbbfc2bdc4dcffc'), name: "Amanda", status: "Updated" }

For more information, see Schema Validation.