Skip to content
MongoDB

Collections & Schema

Manage collections, validators, and capped collections.

By EZ4Code Team
collectionschemavalidation

Code

// Create a collection with a JSON schema validator
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name:  { bsonType: "string" },
        email: { bsonType: "string", pattern: "^.+@.+$" },
        age:   { bsonType: "int", minimum: 0 }
      }
    }
  },
  validationLevel: "strict"
});

// Capped collection (fixed size, circular)
db.createCollection("audit", { capped: true, size: 5242880, max: 5000 });

// Rename and drop
db.users.renameCollection("members");
db.members.drop();

Explanation

MongoDB is schema-flexible, but collection validators enforce a JSON Schema for shape and type safety. Capped collections maintain insertion order and overwrite old documents once the size limit is reached, ideal for log streams. Rename and drop are irreversible administrative operations.

More MongoDB Snippets