MongoDB Collection
A collection is MongoDB's equivalent of a table — a named group of documents that can be created implicitly by an insert or explicitly with configuration options.
What Is a Collection?
A collection groups documents that represent the same kind of entity in your application, such as users, orders, or products. Collections live inside a database and, unlike SQL tables, do not enforce a fixed schema by default — one document can have fields another one lacks entirely, which makes collections a natural fit for evolving data models.
Implicit vs Explicit Collection Creation
Most of the time you never explicitly create a collection — calling insertOne() or insertMany() against a collection name that doesn't exist yet creates it automatically with default settings. You reach for explicit creation, using db.createCollection(), only when you need extra configuration up front, such as a maximum size, a fixed document order, or a validation schema.
Managing Collections
- db.createCollection(name, options) — create a collection explicitly
- show collections — list collections in the current database
- db.collection.renameCollection(newName) — rename a collection
- db.collection.drop() — delete a collection and all its documents
- db.getCollectionInfos() — inspect collection metadata and options
Create a collection with a validator
db.createCollection("reviews", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["rating", "comment"],
properties: {
rating: { bsonType: "int", minimum: 1, maximum: 5 },
comment: { bsonType: "string" }
}
}
}
})Create a capped collection
db.createCollection("activity_log", {
capped: true,
size: 5242880,
max: 1000
})List and drop collections
show collections
db.activity_log.drop()Exercise: MongoDB Collection
What happens if you insert a document into a collection that doesn't exist yet?