What is a Collection in MongoDB?
A collection is MongoDB's equivalent of a table: a group of documents inside a database. No fixed schema — documents in the same collection can have different fields.
Created lazily — the first insert creates it; no
CREATE TABLEstep required.Indexes per collection — including the automatic unique index on
_id.Collection options — capped (fixed size), TTL (auto-expire), schema validation (JSON Schema rules).
Sharded — distributed across shards based on a shard key.
// Create collection implicitly
db.users.insertOne({ name: 'John' }); // Creates 'users' collection
// Create collection explicitly with options
db.createCollection('logs', {
capped: true,
size: 10485760, // 10MB max
max: 10000 // 10,000 documents max
});
// Create time series collection
db.createCollection('metrics', {
timeseries: {
timeField: 'timestamp',
metaField: 'sensorId',
granularity: 'seconds'
}
});
// List collections
db.getCollectionNames();
// Drop collection
db.users.drop();Collections are created automatically on first insert. Capped collections have fixed size — oldest documents are automatically removed when full (useful for logs).
Time series collections optimize storage and queries for time-stamped data. getCollectionNames lists all collections. drop removes a collection entirely.
Collections are schema-flexible (not schema-less — you can enforce schemas with validation). Know capped collections (fixed-size, FIFO) and time series collections (IoT, metrics).
Collections are created implicitly on first insert — no CREATE TABLE needed.