collMod

Definition

  • collMod
  • collMod makes it possible to add options to a collectionor to modify view definitions.

Note

The view modified by this command does not refer to materializedviews. For discussion of on-demand materialized views, see$merge instead.

The commandtakes the following prototype form:

Starting in MongoDB 4.2

  • MongoDB removes the MMAPv1 storage engine and the MMAPv1specific options noPadding and usePowerOf2Sizes forcollMod.
  • The view definition pipeline cannotinclude the $out or the $merge stage. If the view definition includesnested pipeline (e.g. the view definition includes$lookup or $facet stage), thisrestriction applies to the nested pipelinesas well.
  1. db.runCommand( { collMod: <collection or view>, <option1>: <value1>, <option2>: <value2> ... } )

For the <collection or view>, specify the name of a collectionor view in the current database.

Use the userFlags field in thedb.collection.stats() output to check the options enabledfor a collection.

Options

TTL Collections

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

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

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

On success collMod returns a document with fieldsexpireAfterSeconds_old and expireAfterSeconds_new set totheir respective values.

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

Document Validation

  • validator

New in version 3.2.

validator allows users to specify validation rulesor expressions for a collection.For more information, see Schema Validation.

The validator option takes a document that specifies thevalidation rules or expressions. You can specify the expressionsusing the same operators as the query operators with the exception of : $geoNear,$near, $nearSphere, $text, and$where.

Note

  • Validation occurs during updates and inserts. Existingdocuments 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 thevalidation rules to existing documents during an update.

validationLevelDescription"off"No validation for inserts or updates."strict"Default Apply validation rules to all inserts and allupdates."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 oninvalid documents or just warn about the violations but allowinvalid documents.

Important

Validation of documents only applies to those documents asdetermined by the 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 failsvalidation, the write operation logs the validation failure.

To view the validation specifications for a collection, use thedb.getCollectionInfos() method.

Views

Note

The view modified by this command does not refer to materializedviews. 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 thespecified pipeline to this source.

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

Note

The view definition pipeline cannotinclude the $out or the $merge stage. If the view definition includesnested pipeline (e.g. the view definition includes$lookup or $facet stage), thisrestriction applies to the nested pipelinesas well.

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

The view definition is public; i.e. db.getCollectionInfos()and explain operations on the view will include the pipeline thatdefines the view. As such, avoid referring directly to sensitive fieldsand values in view definitions.

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

Write Concern

Optional. A document expressing the write concern of the drop command.

Omit to use the default write concern.

Access Control

If the deployment enforces authentication/authorization, you must havethe following privilege to run the collMod command:

Required Privileges
Modify a non-capped collectioncollMod in the database
Modify a viewcollMod in the database and either:- no find on the view to modify, or- both find on the view to modify andfind 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 theparent database of the specified collection for the duration of theoperation. All subsequent operations on the database and all itscollections must wait until collMod releases the lock.

Examples

Change Expiration Value for Indexes

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

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

Which will return the document:

  1. { "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 namedcontacts.

Note

MongoDB 3.6 adds the $jsonSchema operator to support JSONSchema validation.

  1. db.runCommand( { collMod: "contacts",
  2. validator: { $jsonSchema: {
  3. bsonType: "object",
  4. required: [ "phone" ],
  5. properties: {
  6. phone: {
  7. bsonType: "string",
  8. description: "must be a string and is required"
  9. },
  10. email: {
  11. bsonType : "string",
  12. pattern : "@mongodb\.com$",
  13. description: "must be a string and match the regular expression pattern"
  14. },
  15. status: {
  16. enum: [ "Unknown", "Incomplete" ],
  17. description: "can only be one of the enum values"
  18. }
  19. }
  20. } },
  21. validationLevel: "moderate",
  22. validationAction: "warn"
  23. } )

With the moderate validationLevel, MongoDB appliesvalidation rules to insert operations and to update operationss toexisting documents that already fulfill the validation criteria.Updates to existing documents that do not fulfill the validationcriteria are not checked for validity.

With the warn validationAction, MongoDB logs anyviolations but allows the insertion or update to proceed.

For example, the following insert operation violates the validation rule.

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

However, since the validationAction is warn only, MongoDB onlylogs the validation violation message and allows the operation toproceed:

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