collMod is a MongoDB database command for changing an existing collection or index. Use it when a collection needs a validator, an existing index needs to enforce uniqueness, or an existing single-field index needs a time-to-live (TTL) setting. section 5.4.1 section 7.2.1 section 7.4.3
To add validation, pass the collection name as collMod and put the rules in validator. A $jsonSchema validator can require fields and constrain their types and values. With validationLevel set to moderate, new documents and updates to already-compliant documents are checked while existing noncompliant data can remain. Set validationAction to error to reject operations that fail validation. Changing the validator requires privileges such as dbAdmin on the database or dbAdminAnyDatabase. section 5.4.1
To turn an existing nonunique email index into a unique index:
- Check the index with getIndexes(), then run collMod with index.keyPattern set to { email: 1 } and prepareUnique: true. This prevents new duplicate email values. section 7.2.1
- Run collMod with unique: true and dryRun: true to find existing duplicates without applying the unique constraint. Resolve any duplicates it identifies. section 7.2.1
- Run the unique: true command again without dryRun to complete the conversion. section 7.2.1
db.runCommand({
collMod: "users",
index: {
keyPattern: { email: 1 },
unique: true
},
dryRun: true
})
The dry-run command shows how to identify the index by keyPattern and test a unique conversion before committing it. section 7.2.1
For TTL, use collMod with index.keyPattern and expireAfterSeconds to convert an existing single-field index or change its expiration period; createIndex() cannot change that period on an existing index. Plan the change carefully: many documents may qualify for deletion at once and strain the server. Consider off-peak timing or deleting qualifying documents in batches first. TTL does not apply to compound indexes or the _id field. section 7.4.3
db.getSiblingDB('sample_analytics').runCommand({
"collMod": "transactions",
"index": {
"keyPattern": { "date": 1 },
"expireAfterSeconds": 31536000 // 1 year in seconds
}
})
The command targets an existing date index and sets expireAfterSeconds to one year. section 7.4.3
