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
Insert & Find
Insert documents and query a collection.
Query Operators
Use comparison, logical, array, and regex operators.
Aggregation Pipeline
Build multi-stage pipelines for analytics.
Indexes
Create single, compound, and text indexes for performance.
Update & Delete
Modify and remove documents with update operators.
Replica Set
Configure a replica set for high availability.