Skip to content
MongoDB

Collections & Schema

Manage collections, validators, and capped collections.

#collection#schema#validation

Code

mongodb
// 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();