How to use collMod in MongoDB runCommand()?

The collMod command allows you to modify options for an existing collection or update view definitions in MongoDB. You can execute this command using runCommand() to change collection behavior and properties.

Syntax

db.runCommand({
    collMod: "collectionName",
    option: value
});

Sample Data

Let us first create a collection with sample documents ?

db.demo13.insertMany([
    {"StudentFirstName": "Chris"},
    {"StudentFirstName": "David"},
    {"StudentFirstName": "Bob"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e0f730ad7df943a7cec4fa6"),
        ObjectId("5e0f7310d7df943a7cec4fa7"),
        ObjectId("5e0f7313d7df943a7cec4fa8")
    ]
}

Display all documents from the collection ?

db.demo13.find();
{ "_id": ObjectId("5e0f730ad7df943a7cec4fa6"), "StudentFirstName": "Chris" }
{ "_id": ObjectId("5e0f7310d7df943a7cec4fa7"), "StudentFirstName": "David" }
{ "_id": ObjectId("5e0f7313d7df943a7cec4fa8"), "StudentFirstName": "Bob" }

Example: Using collMod with runCommand

Modify the collection to disable power-of-2 sizes allocation ?

db.runCommand({
    collMod: "demo13",
    usePowerOf2Sizes: false
});
{
    "usePowerOf2Sizes_old": true,
    "usePowerOf2Sizes_new": false,
    "ok": 1
}

Key Points

  • The collMod command modifies collection-level options without recreating the collection.
  • Common options include usePowerOf2Sizes, validator, and validationLevel.
  • The response shows both old and new values for the modified option.

Conclusion

Use runCommand() with collMod to modify collection properties efficiently. This approach allows you to update collection behavior without affecting existing documents or recreating the collection structure.

Updated on: 2026-03-15T02:26:47+05:30

853 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements